开发者

Delete uploaded files

I'm building a web site, using PHP on a linux machine. The client can upload files that I move to a permanent location. Obviously the server cannot contain the files forever.

I'm thinking abo开发者_如何学编程ut using a script that will erase files older than a few hours.

How can I accomplish this?

Thanks,

tzvi.


Two possible solutions :

  • You could loop over the files on the disk, testing the last modification time for each one of them -- and delete the oldest ones.
    • A first solution would be to work with opendir()/readdir()/closedir(), and filemtime().
    • Another idea would be to work with iterators : DirectoryIterator or RecursiveDirectoryIterator, and SplFileInfo::getMTime().
  • Or, you could use a database, and :
    • Add a row to it each time a file is uploaded, containing the current time and date
    • And use that database to determine which file are old enough to be deleted.


The second idea is probably better than the first one :

  • Yes, it means a bit more work right now, when you have to code the system
  • But, if you have lots of files, going through all of them to find the old ones, with the first solution, will not be fast -- and might slow down your server for a while, when the disks are working, seeking for files.


Note that the first solution could be enhanced quite a bit :

  • Use a different folder for each day and hour (2011-04-10-10, 2011-04-11, 2011-04-10-12, ...)
  • And, then, only delete the directories (and their content) which are old enough

With that, no need to search for files : just search for a couple of directories.


If you have shell access to the server, you can use a cron job that calls a (ba)sh script to find and delete files based on time. The following script find files that was uploaded the last 24 hours, recursively in /public_html/YOUR-FOLDER folder and deletes them

#!/bin/bash

find /public_html/YOUR-FOLDER -type f -mtime +1 -exec rm {} \;

On the other hand, if you keep a database record for each uploaded file, you can also use a cron job that calls a php file to delete files based on timestamp


You can create a cron job, which will execute every hour, and in that cron job you will check the timestamps of files when they are created, and based on that you can move your files to some backup folder. You can write the cron job in PHP or a shell script.


I think you can test out below code if you want to do it PHP way. filePath can be your permanent location where you save files. You can modify time based on your requirement.

        foreach(glob($filePath . '*') as $filename)
        {
            if((filemtime($filename) + 2 * 24 * 60 * 60) < time())
                unlink($filename);          
        }

And use it in cron job to delete on specific time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜