Add number to fopen link if that file name already exists - php

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);

Related

Generate a new .txt file every 24 hour

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);
?>

PHP to Increase counter by 1 and save in a txt file

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);
}

Create html file with php script

I want to create a php script that will check if a certain html file exist or not. if it doesn't exist, then create a new one and give it a name.
I have tried the code below, but still not working.
$file = file_get_contents(site_url('appraisal/createReport'));
$filename = 'Service_delivery_report_'.date('Y-m-d', time()).'.html';
$filepath = dirname(__DIR__).'/views/sd_reports/'.$filename;
write_file($filepath, $file);
if(! file_exists ($filename))
{
$fp = fopen($filename, 'w');
fwrite($fp, $file);
fclose($fp);
}
I'm not familiar with the method you're using called 'site_url'. From a quick google search it looks like it's a method in Word Press. Ignoring the site_url method, you might want to test using a specific url, like http://ted.com for example. I've specified is_file rather than file_exists because file_exists will return true even if the path you've specified is a directory, whereas is_file will only return true if the path is an actual file. Try this code, setting the $site variable to a site url or path to a file.
I've also switched some code around, doing a check first to see if the file exists before attempting to read in the contents of $site. This way, if the file already exists, you're not needlessly reading in the contents of $site.
$filename = "Service_delivery_report_" . date("Y-m-d",
time()). ".html";
$filepath = realpath("./") . "/views/sd_reports/" . $filename;
if (!is_file($filepath))
{
$site = "http://somesite.com/somepage";
if ($content = file_get_contents($site))
{
file_put_contents($filepath,
$content);
}
else
{
echo "Could not grab the contents of some site";
}
}
Use file_exists();
<?php
$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>
Then, if it doesn't exist, create a file with fopen();, like so:
$handle = fopen($filename, "w");
Try this
$file = file_get_contents(site_url('appraisal/createReport'));
$filename = 'Service_delivery_report_'.date('Y-m-d', time()).'.html';
if(! file_exists ($filename))
{
$f = fopen($filename, "w");
fwrite($f, $file);
fclose($f);
}
else
echo "file already exist";

How do I prepend file to beginning?

In PHP if you write to a file it will write end of that existing file.
How do we prepend a file to write in the beginning of that file?
I have tried rewind($handle) function but seems overwriting if current content is larger than existing.
Any Ideas?
$prepend = 'prepend me please';
$file = '/path/to/file';
$fileContents = file_get_contents($file);
file_put_contents($file, $prepend . $fileContents);
The file_get_contents solution is inefficient for large files. This solution may take longer, depending on the amount of data that needs to be prepended (more is actually better), but it won't eat up memory.
<?php
$cache_new = "Prepend this"; // this gets prepended
$file = "file.dat"; // the file to which $cache_new gets prepended
$handle = fopen($file, "r+");
$len = strlen($cache_new);
$final_len = filesize($file) + $len;
$cache_old = fread($handle, $len);
rewind($handle);
$i = 1;
while (ftell($handle) < $final_len) {
fwrite($handle, $cache_new);
$cache_new = $cache_old;
$cache_old = fread($handle, $len);
fseek($handle, $i * $len);
$i++;
}
?>
$filename = "log.txt";
$file_to_read = #fopen($filename, "r");
$old_text = #fread($file_to_read, 1024); // max 1024
#fclose(file_to_read);
$file_to_write = fopen($filename, "w");
fwrite($file_to_write, "new text".$old_text);
Another (rough) suggestion:
$tempFile = tempnam('/tmp/dir');
$fhandle = fopen($tempFile, 'w');
fwrite($fhandle, 'string to prepend');
$oldFhandle = fopen('/path/to/file', 'r');
while (($buffer = fread($oldFhandle, 10000)) !== false) {
fwrite($fhandle, $buffer);
}
fclose($fhandle);
fclose($oldFhandle);
rename($tempFile, '/path/to/file');
This has the drawback of using a temporary file, but is otherwise pretty efficient.
When using fopen() you can set the mode to set the pointer (ie. the begginng or end.
$afile = fopen("file.txt", "r+");
'r' Open for reading only; place
the file pointer at the beginning of
the file.
'r+' Open for reading and
writing; place the file pointer at the
beginning of the file.
$file = fopen('filepath.txt', 'r+') or die('Error');
$txt = "/n".$string;
fwrite($file, $txt);
fclose($file);
This will add a blank line in the text file, so next time you write to it you replace the blank line. with a blank line and your string.
This is the only and best trick.

Find out if a directory exists in php

I want to know whether or not a directory exists.
If not, I would like to create the directory.
My code is below:
$da = getdate();
$dat = $da["year"]."-".$da["mon"]."-".$da["mday"];
$m = md5($url)."xml";
if(is_dir($dat))
{
chdir($dat);
$fh = fopen($m, 'w');
fwrite($fh, $xml);
fclose($fh);
echo "yes";
}
else
{
mkdir($dat,0777,true);
chdir($dat);
$fh = fopen($m, 'w');
fwrite($fh, $xml);
fclose($fh);
echo "not";
}
Use is_dir, which checks whether the path exists and is a directory then mkdir.
function mkdir_if_not_there($path) {
if (!is_dir($path)) {
// Watch out for potential race conditions here
mkdir($path);
}
}
Use is_dir:
$pathname = "/path/to/dir";
if(is_dir($pathname)) {
// do something
}

Categories