4

I'm frustrated about deleting file in ubuntu using PHP unlink().

I created a very simple simulation as follow:

  1. create a folder named "files" beneath /var/www with 766 permission.
  2. upload a file, let say "image.png" in that folder & set the permission into 666
  3. create a php file named delete.php, set the permission to 644 and upload to /var/www directory
  4. Call the file in browser (I use localhost)

The "image.png" still exists in "files" directory

Here is the php script of delete.php :

$filename = 'image.png';
$file = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR . $filename;
unlink($file);

I also tried the following script :

$filename = 'image.png';
$dir = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'files';
chdir($dir);
unlink($filename);

But still can't delete the file.

j0k
  • 22,600
  • 28
  • 79
  • 90
user1134475
  • 415
  • 1
  • 8
  • 18

2 Answers2

5

Unlink throws a warning on failure. Check if E_WARNING is visible for you to find out whats going on.

It usually boils down to user rights. Keep in mind if your script is executed by a browser, usually a user named wwwrun or wwwdata (or something similar) is executing it on your server.

Check if this user has permissions to delete, then try again.

Bjoern
  • 15,934
  • 4
  • 43
  • 48
2

The folder/owner of the directory could be a different user than the user being used to run php.

You should create a folder with the user php assigned. If you cannot do that yourself ask your ISP to do it. That is how I solved a similar problem.

One user cannot delete files of another user on a unix system. If you would set it to 777 then you could delete it...

Tschallacka
  • 27,901
  • 14
  • 88
  • 133
  • 1
    If you can SSH to the machine then perhaps you can run `ll` command to see the ownership of the file from which you are deleting and the file which you are deleting. Usually your php scripts are owned by ftp user and uploaded files by root user. It would help to bring them both inside one usergroup. – Khuram Feb 21 '13 at 07:54
  • The file can be deleted when I change the ownership into www-data. Thanks all for the help. – user1134475 Feb 22 '13 at 01:33