简体   繁体   中英

can't get PHP unlink() to work

I have been trying, using PHP, to delete an image file from my image file directory on my Apache server. I can't get it to work. I keep getting the message "successfully deleted", but when I check the image file, it is still there. I suspect that the directory does not allow me access to unlink a file. But I am lost how I tell the server to allow me to unlink a file in the image file directory. I am running XAMMP (Apache server) on a MacBook Air. This is my code:

// DELETE THE PREVIOUS IMAGE FILE TO KEEP DISC USE TO A MINIMUM
$old_image_file = $_SESSION['previous_value']; // IMAGE FILE TO BE DELETED
echo "<p>old_image_file = ".$old_image_file."</p>";

// NAME IMAGE FILE TO BE DELETED AND INDICATE IN WHICH FOLDER IT SITS
$filename_to_be_deleted = '/files/image/'.$old_image_file;
echo "<p>$filename_to_be_deleted = ".$filename_to_be_deleted."</p>";

// CHECK IF FILE EXISTS BEFORE DELETING IT
if (file_exists($filename_to_be_deleted))
{
    unlink(realpath($filename_to_be_deleted)); // DELETE THE FILENAME
} 
// CHECK IF FILE STILL EXISTS OR NOT
if (file_exists($filename_to_be_deleted))
{
    echo "<p>File was not deleted! " . $filename_to_be_deleted."</p>";
} 
else
{
    echo "<p>Successfully deleted " . $filename_to_be_deleted."</p>";
}

It's either path or CHMOD problem, let's find out.

Check unlink result with:

echo unlink(realpath($filename_to_be_deleted)); //returns true or false

If true is returned do the following and you should see the difference

echo realpath($filename_to_be_deleted);
echo $filename_to_be_deleted;

If false is returned make sure the containing directory's CHMOD is set to allow file deletion.

EDIT : Oh of course, follow Fred -ii- 's advice on using error_reporting() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM