Search code examples
phpruntime-errorunlink

Receiving unlink() error after it has been successful


this might be a really stupid question but I am getting the following error after the code has successfully deleted the file and I can not work out why, the code is very simple it gets the name and path of the file to be deleted from the database and then deletes it.

Code:

$getFiles = mysql_query("SELECT * FROM tempFiles WHERE pTID='$passedId'");
$numFiles = mysql_num_rows($getFiles);

for ($f=0;$f<$numFiles;$f++) {

    $fileName = mysql_result($getFiles,$f,"fileName");
    $deleteFile = "../../".$fileName;
    unlink($deleteFile);

}

Warning: unlink(../../files/projects/files/643115.jpg): No such file or directory

The script for deleting the file is in a scripts/php/thefile and the file is in files/projects/files/thefile, so the ../../ is definitely needed and not the issue as far as I can tell. I know that the file is being deleted successfully because it is no longer in the folder after I run the script so I have no idea what is causing the error.

Any ideas why I might be getting the error?

Thank you in advance.


Solution

  • Possible causes to the error:

    • There are more than 1 record in the tempFiles table with the same fileName, so the first attempt removes it and the second causes the error.
    • The file didn't exists on the folder when you ran the script (as @AxelAmthor said on comment)

    To solve it, just add a verification (as @Sammitch said on comment):

    if (is_file($deleteFile)) {
        unlink($deleteFile);
    }