Search code examples
phpfile-iounlink

Unlink() not working


I am trying to delete a file from the Server.

The files of my application is in a folder name "/public_html/app/";

All the images associated with the application is located in the following path: "/public_html/app/images/tryimg/"

The file in which I am writing the below code spec is in "/public_html/app/".

Here is my code snipet:

<?php

$m_img = "try.jpg"

$m_img_path = "images/tryimg".$m_img;

if (file_exists($m_img_path))
{
     unlink($m_img_path);
}
// See if it exists again to be sure it was removed
if (file_exists($m_img))
{
          echo "Problem deleting " . $m_img_path;
}
else
{
        echo "Successfully deleted " . $m_img_path;
}
?>

When the above script is executed the message "Successfully deleted try.jpg" is displayed.

But when I navigate to the folder, the file is not deleted.

Apache: 2.2.17 PHP version: 5.3.5

What am I doing wrong?

Do I have to give a relative or absolute path to the image?


Solution

  • you're missing a directory separator:

    $m_img = "try.jpg"
    
    $m_img_path = "images/tryimg".$m_img;
    
    // You end up with this..
    $m_img_path == 'images/tryimgtry.jpg';
    

    You need to add a slash:

    $m_img_path = "images/tryimg". DIRECTORY_SEPARATOR . $m_img;
    

    You also need to change your second file_exists call as you're using the image name and not the path:

    if (file_exists($m_img_path))