How to delete a file via PHP?

Ken picture Ken · Mar 3, 2010 · Viewed 326.9k times · Source

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?

Answer

Gordon picture Gordon · Mar 3, 2010

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.