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);
}
Related
I'm trying to delete one line from CSV file by its line number, which I get as a parameter in URL.
I saw some discussions here, but it was mainly "delete a line by its id stored in first column" and so on. I tried to make it in the same way as others in these discussions, but it does not work. I only changed the condition.
if (isset($_GET['remove']))
{
$RowNo = $_GET['remove']; //getting row number
$row = 1;
if (($handle = fopen($FileName, "w+")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE)
{
//Here, I don't understand, why this condition does not work.
if ($row != $RowNo)
{
fputcsv($handle, $data, ';');
}
$row++;
}
fclose($handle);
}
}
I supposed, that it should work for me too, BCS just condition was changed. But it does not. It clears the whole file. Could you help me with it, please?
Thank you very much for any advice. Daniel.
You could load the file as an array of lines by using file().
Then remove the line and write the file back.
// read the file into an array
$fileAsArray = file($FileName);
// the line to delete is the line number minus 1, because arrays begin at zero
$lineToDelete = $_GET['remove'] - 1;
// check if the line to delete is greater than the length of the file
if ($lineToDelete > sizeof($fileAsArray)) {
throw new Exception("Given line number was not found in file.");
}
//remove the line
unset($fileAsArray[$lineToDelete]);
// open the file for reading
if (!is_writable($fileName) || !$fp = fopen($fileName, 'w+')) {
// print an error
throw new Exception("Cannot open file ($fileName)");
}
// if $fp is valid
if ($fp) {
// write the array to the file
foreach ($fileAsArray as $line) {
fwrite($fp, $line);
}
// close the file
fclose($fp);
}
If you have a unix system you could also use sed command:
exec("sed -e '{$lineToDelete}d' {$FileName}");
Remember cleaning command parameters if user input used:
https://www.php.net/manual/de/function.escapeshellcmd.php
Option if your CSV can fit to memory:
// Read CSV to memory array
$lines = file($fileName, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
// Remove element from array
unset($lines[$rowNo - 1]); // Validate that element exists!
// Rewrite your CSV file
$handle = fopen($fileName, "w+");
for ($i = 0; $i < count($lines); $i++) {
fputcsv($handle, $data, ';');
}
fclose($handle);
Option if your CSV can not fit to memory:
Use code from question, just write to separate file and later replace it with actual file:
$handle = fopen($FileName, "r");
// Read file wile not End-Of-File
while (!feof($fn)) {
if ($row != $RowNo) {
file_put_contents($FileName . '.tmp', fgets($fn), FILE_APPEND);
}
$row++;
}
fclose($handle);
// Remove old file and rename .tmp to previously removed file
unlink($FileName);
rename($FileName . '.tmp', $FileName);
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'm trying to increment a counter in a multiple text file when a user visit my page, but the code I'm working is not working below is the code
$files = glob("counters/visit/*.txt");
foreach($files as $file) {
$content = file_get_contents($file);
if(!isset($_SESSION['hasVisited'])){
$_SESSION['hasVisited']="yes";
$content++;
$f = fopen($files, "w");
fwrite($f, $content);
fclose($f);
}
}
First make sure that $contentis an integer by doing the following :
$content = intval(file_get_contents($file));
Then you're using :
$f = fopen($files, "w");
Instead of :
$f = fopen($file, "w");
fopen can't accept an array as parameter
Also as mentioned by #alanlittle, if you want all your files to be incremented, you should think about the moment where you set $_SESSION['hasVisited']="yes"; and put it at the end of the loop.
I want to take one text file, split it in half, and put one half in one file, then the remaining half in the next. How would one accomplish this?
an example would be: split.php?n=file.txt
$file = $_GET['n'];
$i = 1;
$fp = fopen("./server/php/files/".$file,'a+');
$fs = filesize("./server/php/files/".$file);
$lengthhalf = $fs / 2;
while(! feof($fp)) {
$contents = fread($fp,$lengthhalf);
file_put_contents('./server/php/files/[2]'.$file,$contents);
$i++;
}
This does the work, without reading the whole file (or half of it) at once in memory:
function split_in_halves($file, $half1, $half2) {
$size = filesize($file);
$fd = fopen($file, 'rb');
stream_copy_to_stream($fd, fopen($half1, 'wb'), $size/2);
stream_copy_to_stream($fd, fopen($half2, 'wb'));
}
split_in_halves('foo', '[1]foo', '[2]foo');
Basically, I want to continue adding numbers each time the file already existed. So if $url.php exists, make it $url-1.php. If $url-1.php exists, then make it $url-2.php, and so forth.
This is what I already came up with, but I think it'll only work the first time.
if(file_exists($url.php)) {
$fh = fopen("$url-1.php", "a");
fwrite($fh, $text);
} else {
$fh = fopen("$url.php", "a");
fwrite($fh, $text);
}
fclose($fh);
I use while loops for scenarios like this.
$filename=$url;//Presuming '$url' doesn't have php extension already
$fn=$filename.'.php';
$i=1;
while(file_exists($fn)){
$fn=$filename.'-'.$i.'.php';
$i++;
}
$fh=fopen($fn,'a');
fwrite($fh,$text);
fclose($fh);
All that said, this direction of solutions does not scale well. You do not want to be checking over a 100 file_exists routinely.
Use a while loop with a counter variable $i. Keep incrementing the counter until file_exists() returns false. At that point, the while loop exits and you call fopen() on the filename with the current value for $i;
if(file_exists("$url.php")) {
$fh = fopen("$url-1.php", "a");
fwrite($fh, $text);
} else {
$i = 1;
// Loop while checking file_exists() with the current value of $i
while (file_exists("$url-$i.php")) {
$i++;
}
// Now you have a value for `$i` which doesn't yet exist
$fh = fopen("$url-$i.php", "a");
fwrite($fh, $text);
}
fclose($fh);
i was looking for something similar like this and extended Shad's answer for my needs. i need to make sure that a fileupload doesn't overwrite files which already exist on a server.
i know it's not "save" yet, cause it doesn't handle files without extension. but maybe it is a little help for somebody.
$original_filename = $_FILES["myfile"]["name"];
if(file_exists($output_dir.$original_filename))
{
$filename_only = substr($original_filename, 0, strrpos($original_filename, "."));
$ext = substr($original_filename, strrpos($original_filename, "."));
$fn = $filename_only.$ext;
$i=1;
while(file_exists($output_dir.$fn)){
$fn=$filename_only.'_'.$i.$ext;
$i++;
}
}
else
{
$fn = $original_filename;
}
<?php
$base_name = 'blah-';
$extension = '.php';
while ($counter < 1000 ) {
$filename = $base_name . $counter++ . $extension;
if ( file_exists($filename) ) continue;
}
$fh = fopen($filename, "a");
fwrite($fh, $text);
fclose($fh);