PHP - unlink('file_name')不工作[重复]

This question already has an answer here:

I have issues while trying to delete files in PHP, using unlink('filename'). I have tried with a complexe file and it didn't worked. I've been using relative paths as adviced on other post about this.

So i've made the simpliest script possible :

<?php
unlink("acs.gif");
?>

The script is located in the same folder as my asc.gif is, tho it still doesn't work. I've got no fatal errors, and a warning when enabling error_reporting() and init_set(). But the file is still there.

I've tried to set the permissions to both my folder, my image and my script to 0777 but it didn't help.

I'm getting quite confused about what is happening.

Do you guys have any ideas ?

</div>

You shouldn't use relative path to file. If it lies in the same folder as a PHP script, use unlink(__DIR__ . '/' . $filename);. In other cases set a full path to unlink.

I recommend you to use absulte filepaths. In case you want to delete a file which is in the same directory of the called script, poleteaw answer should work (besides the missing / in the path):

unlink(__DIR__ . '/' . $filename);

Nevertheless take look of php's directory function realpath() and the predefined constants.

So what if you want to delete a file which is not inside your directory:

  1. You can use the realpath() method to generate an absolute path out of a relative path. So realpath('/one/two/three/../..') results in '/one' - or for your case you can do something like realpath(__DIR__ . '/../../') to get into the root directory of you project.
  2. The recommended way is to use a variable which holds the absolute path to the directory where you want to store and administrate your files like $filesDir = '/path/to/my/files'. With this approach you have two wins: your users files do not reside in your php project files and you have a way much better overview of which files are uploaded/administrated.