Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php script to delete files older than 24 hrs, deletes all files

I wrote this php script to delete old files older than 24 hrs, but it deleted all the files including newer ones:

<?php   $path = 'ftmp/';   if ($handle = opendir($path)) {      while (false !== ($file = readdir($handle))) {         if ((time()-filectime($path.$file)) < 86400) {              if (preg_match('/\.pdf$/i', $file)) {               unlink($path.$file);            }         }      }    } ?> 
like image 806
ChuckO Avatar asked Jun 27 '10 02:06

ChuckO


People also ask

How do you automatically delete files then older?

Use this command: ForFiles /p “C:\path\to\folder” /s /d -30 /c “cmd /c del /q @file”. Change “30” for the number of days you want and the folder path.

How can I delete all files in a directory in PHP?

If you want to delete everything from folder (including subfolders) use this combination of array_map , unlink and glob : array_map( 'unlink', array_filter((array) glob("path/to/temp/*") ) );

How do I delete files with names that are too long?

The trick is to auto-generate a shorter filename and use that. Open a command prompt in the directory where the file is located. Use a DOS command to get the short filename in the 8.3 filename format. Now, use the DEL command in DOS for the file to delete the file.

What is the PHP command for deleting a file?

Description ¶ There is no delete keyword or function in the PHP language. If you arrived at this page seeking to delete a file, try unlink(). To delete a variable from the local scope, check out unset().


1 Answers

<?php  /** define the directory **/ $dir = "images/temp/";  /*** cycle through all files in the directory ***/ foreach (glob($dir."*") as $file) {  /*** if file is 24 hours (86400 seconds) old then delete it ***/ if(time() - filectime($file) > 86400){     unlink($file);     } }  ?> 

You can also specify file type by adding an extension after the * (wildcard) eg

For jpg images use: glob($dir."*.jpg")

For txt files use: glob($dir."*.txt")

For htm files use: glob($dir."*.htm")

like image 120
Mike Avatar answered Sep 18 '22 06:09

Mike