nickanor
nickanor

Reputation: 669

PHP: unlink cannot delete file even the file exists and writable

I've been trying to figure out why unlink is not working. I've tried stackoverflow previous questions and answers but no luck. The exact filename that needs to be deleted is 'upload/test.png'. First I made a check if file exists.

$filename = 'upload/test.png';
if(file_exists($filename)){
// file_exists returns true
    if(is_writable($filename)){
        // is_writable also returns true
        if(unlink($filename)){
            echo 'file deleted';
        }
        else{
            echo 'cant delete file';
            print_r(error_get_last());
            // this gives me
            // unlink() function.unlink: No such file or directory
        }
    }
}

Upvotes: 7

Views: 22430

Answers (5)

Clive Miller
Clive Miller

Reputation: 61

I was trying to use my php script to modify a file in a subdirectory of where the script was running. When I tried to delete the file, it was not possible. However, when I moved it to a completely different part of the filesystem, it worked. Seems like a security feature of php (8.1).

Upvotes: 0

AnKov
AnKov

Reputation: 1

I have found out that unlink is sensitive to encoding. I also had such kind of problem, but then I used:

$filename= iconv("UTF-8", "Windows-1251", $filename);

and that worked for me.

Upvotes: 0

Satyam Saxena
Satyam Saxena

Reputation: 571

If you are saying that everything is ok and no permission issue then you can try this way too:

unlink(realpath("upload/test.png"));

Upvotes: 2

Yang
Yang

Reputation: 8701

Give the full path instead, like

$filename = dirname(__FILE__) . '/upload/test.png';

Then try this,

if (is_file($filename)) {

   chmod($filename, 0777);

   if (unlink($filename)) {
      echo 'File deleted';
   } else {
      echo 'Cannot remove that file';
   }

} else {
  echo 'File does not exist';
}

Upvotes: 6

BT643
BT643

Reputation: 3845

Try this and post what output you get (if any).

$filename = 'upload/test.png';

@unlink($filename);

if(is_file($filename)) {
   echo "file was locked (or permissions error)";
}

Upvotes: 0

Related Questions