PHP: Deleting Files

July 14, 2015

To delete all files of a particular extension, or in fact, delete a group with any wildcard,

echo `rm -f path/to/*.jpg`;
# note the backquotes, not single nor double quotes

or


foreach (glob("*.jpg") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
unlink($filename);
}

sometimes, the function realpath() may be needed:
unlink(realpath($fileName));

or

$mask = "*.jpg"
array_map( "unlink", glob( $mask ) );

To anyone who’s had a problem with the permissions denied error, it’s sometimes caused when you try to delete a file that’s in a folder higher in the hierarchy to your working directory (i.e. when trying to delete a path that starts with “../”).
to work around this problem, you can use chdir() to change the working directory to the folder where the file you want to unlink is located.

$old = getcwd(); // Save the current directory
chdir($path_to_file);
echo `rm -f *.jpg`; # or unlink($filename);
chdir($old); // Restore the old working directory
# note the echo with backquotes again

“breaking my head for about an hour on why I couldn’t get my persmissions right to unlink the main file. Finally I knew what was wrong: because I was working on the file and hadn’t yet closed the file, it was still in use and of course couldn’t be deleted :)”

fclose($somefile);
$rmfile = 'rm -f '.$somefile ;
echo `$rmfile`; # or unlink($somefile);

error messages

have php capture and display the error message:


$rmfile = 'rm -f path/to/filename.jpg' 2>&1 1> /dev/null ' ;
$rmerr = shell_exec($rmfile) ;
echo $rmerr ;

Leave a Reply

We try to post all comments within 1 business day