0

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 ?

B.T
  • 521
  • 1
  • 7
  • 26

2 Answers2

4

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.
sics
  • 1,298
  • 1
  • 11
  • 24
  • It did work with the missing `/`. Now what if my file is not in the same folder. Should I use `__FILE__` and remove the name of the file ? – B.T Oct 09 '17 at 12:40
  • 1
    You can use the realpath() to retrieve absolute filepaths out of realtive filepaths. I will write you an example in my answer. – sics Oct 09 '17 at 12:42
  • `__FILE__` without filename is equal `__DIR__` :) Normally I define and use my own constanst (e.g. `FILE_STORAGE_DIR`). And then work with it. – poletaew Oct 09 '17 at 12:45
1

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.

poletaew
  • 197
  • 2
  • 12