Naming a text file as a variable
I have a variable $Date
that is automatically updated each day. I would like to create a new text file each time that there is a new entry. So basically every day.
I would like to use fopen
to create a new text file every time a user submits a value, but only for that day. If a user creates another account the next day, it will be a new text file with that date for a name...
I only have three variables, $date
, $Name
, and $number
Is it possible to create this as follows?
$textmem开发者_运维知识库ber = "$date.txt"
Yes, you could easily create a new text file each day.
$filename = "$date.txt";
if (! file_exists($filename)) {
$fp = fopen($filename,'w');
//write stuff to file
fclose($fp);
}
If you're appending data to the file, you don't even need to do the file_exists()
check, you can just use the 'a' option of fopen()
:
$filename = "$date.txt";
$fp = fopen($filename,'a');
//write stuff and close
In this case, the file will be created if it doesn't exist, and if it does, the data you write will just be appended on the end.
That should be as easy as
file_put_contents($filename, $text, FILE_APPEND);
where $filename should be a combination of $name and $date and $text the data you want to write. You only have to combine $data and $name if you want a file per name and date, e.g.
$filename = sprintf('%s-%s.txt', $date, $name);
So, with $date being 2009-12-30 and $name being Gordon you'd get 2009-12-30-Gordon.txt
. That file would be created if it does not already exist and $text would be written into it. If it already exists, $text would be appended into it, e.g.
$filename = sprintf('%s-%s.txt', date('Y-m-d'), 'Gordon'); // create filename
file_put_contents($filename, 'foo', FILE_APPEND); // create file and write to it
// later that day
file_put_contents($filename, 'bar', FILE_APPEND); // append to existing file
You have to make sure the directory you create the file in is writable.
Check the PHP manual for further reference.
To do that you can create the file with a especified format everyday and check if the file doesnt exists already, if it doesnt then create it. I would use the format $username-$date, so a file for the username ryudice would look like "ryudice-22-2-2009.txt", then you can check if the file exists every time the user submits a value, if it doesnt exist then create it, to check if the file already exists you can use the file_exists function.
If you're using PHP 5+...
$filename = 'data/textmembers/date/' . $Date . '.txt';
file_put_contents($filename, $Name, FILE_APPEND);
file_put_contents($filename, $Number, FILE_APPEND);
If your script is located in /var/www/html/my_script.php then the file will be saved at /var/www/html/data/textmembers/date/$Date.txt . You will need to make sure that directory (/path/to/date) has write permissions for the user PHP runs under.
精彩评论