How to delete a file via PHP?

How do I delete a file from my server with PHP if the file is in another directory?

Here is my page layout:

  • projects/backend/removeProjectData.php (this file deletes all my entries for the database and should also delete the related file)
  • public_files/22.pdf (the place where the file is located.)

I'm using the unlink function:

unlink('../../public_files/' . $fileName);

But this always gives me an error that the file does not exist. Any ideas?


Solution 1:

The following should help

  • realpath — Returns canonicalized absolute pathname
  • is_writable — Tells whether the filename is writable
  • unlink — Deletes a file

Run your filepath through realpath, then check if the returned path is writable and if so, unlink it.

Solution 2:

$files = [
    './first.jpg',
    './second.jpg',
    './third.jpg'
];

foreach ($files as $file) {
    if (file_exists($file)) {
        unlink($file);
    } else {
        // File not found.
    }
}

Solution 3:

Check your permissions first of all on the file, to make sure you can a) see it from your script, and b) are able to delete it.

You can also use a path calculated from the directory you're currently running the script in, eg:

unlink(dirname(__FILE__) . "/../../public_files/" . $filename);

(in PHP 5.3 I believe you can use the __DIR__ constant instead of dirname() but I've not used it myself yet)

Solution 4:

You can delete the file using

unlink($Your_file_path);

but if you are deleting a file from it's http path then this unlink is not work proper. You have to give a file path correct.