I would like to be able to copy a text file that’s on my server, edit it based on the user input, and allow them to download the new file, but then delete it either after their session is done, or a certain amount of time.
I know how to copy and edit files, but I don’t know how to make temporary files or a temporary directory, or how to dynamically name them… If multiple people are making files at once, I don’t want to run into problems with making two files of the same name.
I’ve tried searching, but I’m not exactly sure how to phrase it. I’ve come across some pages on the PHP site about temporary files that are deleted as soon as the PHP stops running, but that wouldn’t allow the users to download the file.
What exactly I would like to know:
-How to dynamically name copies of server files that are automatically deleted after a certain amount of time.
edit: Sorry, I know this might be more of a website problem than PHP, but I’m new to both.
You can use
tempnam()to create a unique filename:http://www.php.net/manual/en/function.tempnam.php
There is also
tmpfile(), which does the same, except that it a) Also creates the file and returns a file handle instead of a filename and b) automaticlly deletes the file atfclose()or when the script ends.If you want to copy a file, then
tempnam()would probably be the best suited.You can delete the files manually at the end of the script, or just use a cronjob to delete them if there more than a day old. If you can’t set cronjobs, you can create a “adminpage” and fetch it every day orso using a cronjob (Or scheduled task) from another machine.
To answer the question “How do I delete old files”:
First, you will probably want to set the
$prefixargument fortempnam()to a “separate” directory. By default, it’ll typically use/tmp/which holds lots of other stuff. Use/tmp/mydir/(Make sure to check if it exists before writing to it!) or something in your home directory.After that, you have two methods to find and clean up the files.
The first is using
find, this is a powerful commandline tool which, as you might of guessed, finds files. As command fill in:To briefly explain:
-type fmeans it only matches files (and not directories),-mtime -1dmeans it only matches files with a modification date of minus 1 day ago. And finally-deletewill delete the file.findis very powerful and useful, but may also be a bit daunting.Another method is writing your own (PHP) script to search for files and call that. You can use
scandir()to get a list of a directory contents, andstat()to get various info about files (Such as modification date).