How to delete a file via PHP?

ID : 20121

viewed : 25

Tags : phpfile-iophp

Top 5 Answer for How to delete a file via PHP?

vote vote


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.

vote vote


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


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)

vote vote


You can delete the file using


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.

vote vote


AIO solution, handles everything, It's not my work but I just improved myself. Enjoy!

/**  * Unlink a file, which handles symlinks.  * @see  * @param string $filename The file path to the file to delete.  * @return boolean Whether the file has been removed or not.  */ function unlinkFile ( $filename ) {     // try to force symlinks     if ( is_link ($filename) ) {         $sym = @readlink ($filename);         if ( $sym ) {             return is_writable ($filename) && @unlink ($filename);         }     }      // try to use real path     if ( realpath ($filename) && realpath ($filename) !== $filename ) {         return is_writable ($filename) && @unlink (realpath ($filename));     }      // default unlink     return is_writable ($filename) && @unlink ($filename); } 

Top 3 video Explaining How to delete a file via PHP?