Ad Code

Delete All Files from Folder using PHP

PHP code is provided for three situations. In these situations, you should need to delete all files functionality in your web project.

Delete All Files from Folder:
The following script removes all files from the folder.

$files = glob('my_folder/*'); //get all file names
foreach($files as $file){
    if(is_file($file))
    unlink($file); //delete file
}

 

Delete All Files of Specific Type Recursively from Folder:
The following script removes only those files which have a specific extension.

$files = glob('my_folder/*.jpg'); //get all file names
foreach($files as $file){
    if(is_file($file))
    unlink($file); //delete file
}

 
Delete Old Files from Folder:
The following script removes the files which modified before the specified time.

$files = glob('my_folder/*'); //get all file names
foreach($files as $file){
    $lastModifiedTime = filemtime($file);
    $currentTime = time();
    $timeDiff = abs($currentTime - $lastModifiedTime)/(60*60); //in hours
    if(is_file($file) && $timeDiff > 10) //check if file is modified before 10 hours
    unlink($file); //delete file
}


 

Post a Comment

0 Comments