Search code examples
phpunlink

unable to unlink file in php


On a website I'm trying to implement a utility that removes selected images from a certain folder using an HTML form with checkbox selection and a php-file that should actually remove the selected images. The form works and the values of the checkbox are parsed into $_POST['images'], the php-code to do the rest:

$dir=__ROOT__."/images/".$_POST['page'];
echo "dir=".$dir."<br>";
$files=array();
$fdir=opendir($dir);
while ($i = readdir($fdir)) {
    //detect images and put them into files()
    if (strpos(strtolower($i),".jpg")==true&&strpos(strtolower($i),".thumb")==false) $files[]=$i;
}
closedir($fdir);
for($a=0;$a<sizeof($files);$a++) {
    if(in_array($files[$a],$_POST['images'])) {
        $file="../images/".$_POST['page']."/".$files[$a];
        echo $file."<br>";
        echo('<img src="'.$file.'.thumb"><br>');
        if(unlink("../images/".$_POST['page']."/".$files[$a])) {
            echo ("deleted: ".$files[$a]."<br>");} 
            else {echo ("deletion of ".$files[$a]." failed<br>");}
        if(unlink("../images/".$_POST['page']."/".$files[$a].".thumb")) echo "deleted: ".$files[$a].".thumb";
    }
}

When trying to delete e.g. IMG_001.jpg (and thumbnail IMG_001.jpg.thumb), I get the following echo-output:

dir={absolute path of the file}
../images/keramiek/IMG_001.jpg
{the correct thumbnail}
deletion of IMG_001.jpg fialed

What's going wrong? Why doesn't unlink() remove the file? I tried with permissions set on 777, but still no success...

SOLUTION:

After changing permissions for the folder containing the images, deletion works as it should. The owner has been changed to www-data and permissions are set to 755.

Newly uploaded images (over FTP) are deletable too.


Solution

  • The solution is to set correct permission like this:

    sudo chown your_user:www-data images/
    sudo find images/ -type d -exec chmod 770 {} +
    sudo find images/ -type f -exec chmod 660 {} +
    

    EDIT (by OP): this will do, but use 775 and 665 instead, or the folder will be inaccessable