Now I am fed up with this issue, have been trying to fix it since 2-3 days.
The problem:
I am downloading certain images, and then writing them on to disk with php script.
The images are high resolution may be around 7000 pixels. The data is being downloaded properly.
When I write this data on to file, some time 1 image gets write, some times 2,3 etc.
The script is not showing any error and just breaks.
I don't have access to server logs and can't check those either.
It breaks after curl_get_contents , means where I write file, if I comment that section it works properly.
Below is the code:
<?php
ini_set ("display_errors", "1");
error_reporting(E_ALL);
ini_set('max_execution_time', 3000);
include_once("../config.php");
include_once("../utils.php");
$DIR = "../wallpapers";
$URL = "Website url";
$info = array();
$dom = new domDocument;
#$dom->loadHTML(file_get_contents($URL));
$dom->preserveWhiteSpace = false;
$links = $dom->getElementsByTagName('img');
$i = 0;
foreach ($links as $tag){
$iurl = $tag->getAttribute('src');
$lastHyphenAt = strrpos($iurl, "-");
$iurl = substr ($iurl, 0, $lastHyphenAt).".jpg";
$info[$i]["url"] = $iurl;
$info[$i]["name"] = basename($iurl);
$i++;
}
foreach($info as $item){
$url = $item["url"];
$name = $item["name"];
if(!file_exists($DIR."/".$name)){
echo "Downloading: ".$url."<br><br>";
$data = curl_get_contents($url);
$file = fopen($DIR."/".$name,"w") or die('Cannot open file: '.$my_file);
fwrite($file,$data);
fclose($file);
}else
echo "Exists ".($DIR."/".$name)."<br><br>";
}
?>
you can write high resolution images by applying chunk functionality, check below code for the same :-
$chunk = 102400;
$filePointer = fopen($url, "rb");
if ($filePointer!=false){
while (!feof($filePointer))
{
if($chunk<TOTALFILESIZE)
{
$fileData = fread($filePointer, 102400); //102400 is chunk size
$myFile = $DIR."/".$_REQUEST['filename'].'.'.$_REQUEST['ext']; //store the file into temp. location
chmod($myFile, 0777);
$fp = fopen($myFile, 'a+');
fwrite($fp, $fileData);
fclose($fp);
}
}
}
Related
I'm trying to make a visitor counter with php that will create yy-mm-dd.txt everyday and contain the number of visitors that day and after 12 AM it will create a new yy-mm-dd.txt file.
As example today is 2019-06-02 so the text file will be 2019-06-02.txt and in the next day, 2019-06-03.txt file will be automatically created.
Here is what I tried but it is not creating new 2019-06-03.txt file after 12 AM. It keeps the same 2019-06-02.txt file
<?php
$date = date('Y-m-d');
$fp = fopen('dates/'.$date.'.txt', "r");
$count = fread($fp, 1024);
fclose($fp);
$count = $count + 1;
$fp = fopen('dates/'.$date.'.txt', "w");
fwrite($fp, $count);
fclose($fp);
?>
How to fix it?
Your code should be working fine. We can also add is_dir and file_exists checks, and we can use either fopen, fwrite and fclose or file_get_content/file_put_content, if we like. We can also add a default_timezone such as:
date_default_timezone_set("America/New_York");
Then, our code would look like something similar to:
date_default_timezone_set("America/New_York");
$dir = 'dates';
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
$count = 1;
$date = date('Y-m-d');
$filename = $dir . '/' . $date . '.txt';
if (!file_exists($filename)) {
$fp = fopen($filename, "w");
fwrite($fp, $count);
fclose($fp);
} else {
$count = (int) file_get_contents($filename) + 1;
if ($count) {
file_put_contents($filename, $count);
} else {
print("Something is not right!");
}
}
Better use file_get_contents then file_put_contents:
<?php
$count = 1;
$content = file_get_contents(date('Y-m-d').'txt');
if($content !== FALSE){
$count+=(int)$content;
}
file_put_contents(date('Y-m-d').'txt', $count);
?>
I am trying my php script to read the current count from "counter.txt" file and add 1 and save it back in the counter text file.
$filename = 'counter.txt';
// create the file if it doesn't exist
if (!file_exists($filename)) {
$counter_file = fopen($filename, "w");
fwrite($counter_file, "0");
$counter = 0;
} else {
$counter_file = fopen($filename, "r");
// will read the first line
$counter = fgets($counter_file);
}
// increase $counter
$counter++;
// echo counter
echo $counter;
// save the increased counter
fwrite($counter_file, "0");
// close the file
fclose($counter_file);
The script reads and echos the number fine but it doesn't save the file with the increased number.
Please help
This may not be helpful if this is just a learning exercise to familiarize yourself with the various file functions, but this could be a lot simpler using file_get_contents and file_put_contents.
$file = 'counter.txt';
// default the counter value to 1
$counter = 1;
// add the previous counter value if the file exists
if (file_exists($file)) {
$counter += file_get_contents($file);
}
// write the new counter value to the file
file_put_contents($file, $counter);
Of course, whether or not this will work either this way or the way you're trying to do it totally depends on whether or not the file is writable, so you'll also need to be sure its permissions are set properly.
Works for me:
$counter = 1;
$file_name = 'test.'.$counter.'.ext';
if (file_exists($file_name)) {
$counter++;
fopen('test'.$counter.'.ext' , "w");
}
else {
fopen('test'.$counter.'.ext' , "w");
}
<?php
$filename = 'counter.txt';
// create the file if it doesn't exist
if (!file_exists($filename)) {
$counter_file = fopen($filename, "w");
fwrite($counter_file, "1");
fclose($counter_file);
} else {
$counter_file = fopen($filename, "w+");
$fsize = filesize($filename);
// will read the whole file
$counter = (int) fread($counter_file, $fsize);
$counter++;
fwrite($counter_file, $counter);
fclose($counter_file);
}
I am extremely new to PHP and am having some issues with my first script. I am attempting to use this PHP script to generate HTML files for a series of products that only have minor changes between them. I have a .csv spreadsheet with all of the information, an html template and the PHP script I will post below.
Here is the problem I am encountering. When I check the folder where the script is supposed to put my finished HTML files after running the script, there are only 4 files instead of the 36 I want it to make. There are 36 rows of information in the .csv and I can't figure out how to get the script to generate all of the HTML files it should.
Here is my script:
<?php
$base_template = file_get_contents('template.html');
$file_to_read = 'spreadsheet.csv';
ini_set("auto_detect_line_endings", 1);
$filename = '';
if (($handle = fopen($file_to_read, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$Column1 = $data[0];
$Column2 = $data[1];
$Column3 = $data[2];
$Column4 = $data[3];
$Column5 = $data[4];
$Column6 = $data[5];
$Column7 = $data[6];
$filename = preg_replace('/[\s\W]+/','',$Column1);
$filename = substr($filename, 0, 10);
$template = str_replace('{Column1}', $Column1, $base_template);
$template = str_replace('{Column2}', $Column2, $template);
$template = str_replace('{Column3}', $Column3, $template);
$template = str_replace('{Column4}', $Column4, $template);
$template = str_replace('{Column5}', $Column5, $template);
$template = str_replace('{Column6}', $Column6, $template);
$template = str_replace('{Column7}', $Column7, $template);
$file = fopen('generated_html/'.$filename.'.html',"w+");
fwrite($file, $template);
fclose($file);
}
fclose($handle);
}
?>
How can I get the script to generate all of the files I need instead of stopping early?
php bulk file read problem in loop.
I have 3 image files which are already on server. Say it is picture1.jpg, picture2.jpg, picture3.jpg
I have this code which read the file but $thepic = fread($fh, $fs); only read last file ( picture3.jpg) in the array.
$imgfolder = "images/";
foreach ($picturefile as $pfile) {
echo $imgpath = "./". $imgfolder.$pfile; // This echo shows all files path when loop run
$picFile = $imgpath;
$fh = fopen($picFile, 'r');
$fs = filesize($picFile);
$thepic = fread($fh, $fs);
echo $thepic; // $thepic variable only show last file.
echo "<br>-----------------------------------------------<br>";
fclose($fh);
}
I recently had an issue... I wanted to transfer my contacts fro my LG U990 Viewty to my iPhone 3GS
I exported the contacts from my LG to a vCard File containing all the addresses all in one as
BEGIN:VCARD
VERSION:2.1
N;CHARSET=UTF-8:A;
TEL;CELL;CHARSET=UTF-8:*121#
REV:20120720T081000Z
END:VCARD
Now the above format repeated itself for all contacts... in that single file...
I wanted to convert this single file to original vcf files... not knowing that they could not be imported to iPhone also :(
Actualy Solution : I needed to upload the original bulk vCard file to a new gmail's accounts contacts and sync my contacts to that list in iTunes... which finally I did
However, I made this code which is in PHP generally available as a paid software which people buy to decipher the contacts... here is the below code... FREE
contacts.txt is that file ... open that vCard file in text editor and copy the contents and make this contacts.txt file
$filename = "contacts.txt";
$fd = fopen ($filename, "r");
$contents = fread ($fd,filesize ($filename));
fclose ($fd);
$delimiter = "BEGIN:VCARD";
$splitcontents = explode($delimiter, $contents);
$counter = "";
$write = "";
$finalName = "";
foreach ( $splitcontents as $color )
{
$counter = $counter+1;
$first = strpos($color, "UTF-8:");
$second = strpos($color, "TEL;");
$name = substr($color, $first+6, $second-$first-7);
$wordChunks = explode(";", $name);
for($i = 0; $i < count($wordChunks); $i++)
{
if(trim($wordChunks[0])!="" || trim($wordChunks[1])!="" )
$finalName .= " ".$wordChunks[$i];
}
$finalName= trim($finalName);
$fileName = $finalName.".vcf";
$ourFileHandle = fopen($fileName, 'w') or die("can't open file");
$stringData = "BEGIN:VCARD ".$color;
fwrite($ourFileHandle, $stringData);
fclose($ourFileHandle);
$finalName = "";
}
this will finally make miltuple .vcf files of format given above...
MY QUESTION : WHAT I DID WAS VERY SIMPLE AND HAS LOOPHOLES - CAN WE DO THE ABOVE ITERATION AND FILTERING IN A PHP REGULAR EXPRESSION ?
it would be a great learning ?
Read the file and get a string of the context
NSData *String_Data = [NSData dataWithContentsOfFile:yourfilepath];
NSString *theString = [[NSString alloc] initWithData:String_Data encoding:NSUTF8StringEncoding];
Get array of all the lines in the context
NSArray *lines = [theString componentsSeparatedByString:#"\n"];
Run for Loop through each line: Check prefix for BEGIN: or END:
NSString * stringForVCard=#"";
for (int i=0; i<[lines count];i++){
[stringForVCard stringByAppendingString:[lines objectAtIndex:i]
if ([line hasPrefix:#"END"])
[stringForVCard writeToFile:[NSString stringWithFormat:#"Make your own file path for each VCF"] atomically:TRUE encoding:NSUTF8StringEncoding error:nil ];
//Empty the string
stringForVCard=#"";}
file structure:
index.php
contacts.vcf
a(folder)
$filename = "contacts.vcf";
$file = file($filename);
$i=1;
$content = "";
foreach ( $file as $line )
{
if($line == 'BEGIN:VCARD'."\r\n"){
$content = "";
}
$content .= $line;
if($line == 'END:VCARD'."\r\n"){
$fileName = $i.".vcf";
$ourFileHandle = fopen('a/'.$fileName, 'w') or die("can't open file");
fwrite($ourFileHandle, $content);
fclose($ourFileHandle);
$i++;
echo '<br>' . $i .'
';
}
}