How to delete a file via PHP? How to delete a file via PHP? php php

How to delete a file via PHP?


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.


$files = [    './first.jpg',    './second.jpg',    './third.jpg'];foreach ($files as $file) {    if (file_exists($file)) {        unlink($file);    } else {        // File not found.    }}


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)