0

I've made a simple script that allows users to upload html files to a web directory on my server. However, I'd like it so each file is deleted after 24 hours of being on my server. 24 hours for each file, not 24 hours for the entire directory. Here is my code so far... Thank you for your help. :)

<?php 
 $target = "users/"; 
 $target = $target . basename( $_FILES['uploaded']['name']) ; 
 $ok=1; 

 if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)
 && ($_FILES["uploaded"]["type"] == "html")) 
 {
 echo "File: " . $_FILES["uploaded"]["name"] . "<br />";
 echo "Type: " . $_FILES["uploaded"]["type"] . "<br />";
 echo "Size: " . ($_FILES["uploaded"]["size"] / 1024) . " Kb<br />";
 echo "Location: /users/" . $_FILES["uploaded"]["name"]; 
 } 

 else {
 echo "Sorry, " . $_FILES["uploaded"]["name"] . " is not a valid HTML document. Please try again.";
 unlink . $_FILES["uploaded"]["name"];
 }
 ?> 
user3742063
  • 11
  • 1
  • 6

4 Answers4

0

Use Cron to execute this script every 10 minutes (better 30 or 60)

$Time=time();
foreach(glob('/users/*') as $file){
    if(filemtime($file)+60*60*24<$Time){
        unlink($file);
    }
}
Cpecific
  • 57
  • 3
0

Not fullproof, but it gives an idea..

foreach(glob("/users/YOUR_USER/*") as $file) {
   $file = "/users/YOUR_USER/".$file;
   if ((time() - filectime($file)) >= 86400) {
      // delete me
   }
}
0

If you're using a Windows server then run a batch file using Windows Scheduler: Batch file to delete files older than N days

Otherwise, just set up a CRON job.

Community
  • 1
  • 1
0

Include following script at the end of your script. Don't forget to replace /var/www/uploads/ with correct path. Other wise all files will be removed in different place.

$files=shell_exec('find /var/www/uploads/ -mmin +1440');
$file = explode("\n",$files);
if(isset($file) && is_array($file))
{
    foreach($file as $val)
    {
        @unlink($val);
    }
}

The above code will work on Linux/UNIX based hosting.

  • "shell_exec" will execute linux command and return the out put
  • "find -mmin -1440" is looking for files older than 1 day or 1440 minutes
  • First line "/var/www/uploads/" path need to be replaced with full path of the directory.
  • Unlink have "@" sign to avoid warning if the file not exists there.
  • As this is powerful linux based command verify the paths correctly.
sugunan
  • 4,408
  • 6
  • 41
  • 66