I am trying to execute a php process file, in a folder where there’s this php file and other files (can be images, text document, pdf, other code files, etc.)
I need to generate a process where detects main image formats and deletes it automatically.
I have this code:
$dirPath = '.';
$files = scandir($dirPath);
foreach ($files as $file) {
$filePath = $dirPath . '/' . $file;
if (is_file($filePath)) {
//echo $file . "<br>";
$file_parts = explode(".", $file);
$file_extension = $file_parts[1];
$image_extensions = array( "jpg", "png", "jpeg", "tiff", "webm", "jpeg", "gif" );
echo "<br />Found this file: ".$file;
foreach($image_extensions as $i_e){
if (strcmp($file_extension, strval($i_e)) === 0) {
chmod ($file, 0777);
unlink($file);
echo 'Deleted for being an image.';
}
}
}
}
But never deletes it. Files have a permissions level of 0644.
Is this a problem? Can I change permissions?
Could be another reason.
All files are in the same folder.
Why files isn’t being deleted?
Thanks in advance.
I was trying to delete all images in a folder and isn’t working.
2
Answers
Having files with permissions set to 644 should not be a problem since the owner has both read and write permissions in PHP. However, check if the file is owned by the user under which your PHP script is running.
Here are some adjustments in your code that might help!
Privileges of 644 means that the owner user has read and write permissions, but no execute, whereas group users and others have read permissions only.
Now, in order to remove a file, you need X (execute) to cd into the file and W (write) to remove them. Hence, the user needs to have either 7 or 5 as a privilege in order to be able to delete the file, see https://www.quora.com/What-exact-permission-is-required-to-delete-a-file-and-directory-in-Linux-What-exact-permission-is-required-to-copy-or-move-a-file-dir-in-Linux
So the permissions by themselves prevent your program from successfully running, which is the technical reason of your problem.
But the real reason is that you either did not set PHP to properly log the errors. You will need to
$files
and whether your code actually tries to remove the files you wanted to removeif (strcmp($file_extension, strval($i_e)) === 0) {
and whether the files you intend to remove successfully pass this conditionunlink
return. Is it returning true, claiming the file was removed, or is it false?Looking into these questions you should be able to solve your problem.