Deleting file from folder

117 views Asked by At

I'm not quite sure where the problem lies. But the code won't unlink the file :(

 <?php include_once("sessions.php");
require_once("connect.php");
if(isset($_POST['delete'])){

$album_id = $_SESSION['album_id'];

$checkbox = $_POST['photo_checkbox'];
$count = count($checkbox);

for($i = 0; $i < $count; $i++) {
    $id = (int) $checkbox[$i]; // Parse your value to integer

    if ($id > 0) { // and check if it's bigger then 0

        $query = "SELECT * FROM media WHERE id = $id";
        $result = mysqli_query($connection, $query);
            while($row = mysqli_fetch_array($result)){

            $file = $row['path'];

                if(!unlink($file)){
                    $_SESSION["edit_message"] = "<br>Something went wrong while deleting shit ... please try your editing again." .$file;
                    header ("Location: ../fotos.php?album=".$album_id."");
                    exit;
                }

            }
        $query = "DELETE FROM media WHERE id = $id";
        $result = mysqli_query($connection, $query);
    }
}   

    if($result){
        $_SESSION["edit_message"] = "<br>Successfully deleted !";
        header ("Location: ../fotos.php?album=".$album_id."");
        exit;}
}

?>

If I take out the unlink loop part and just go straight to the deleting from the db it works fine. What am I missing? Might it be the permissions that are hindering the code from executing ?

EDIT : Changed the permissions of the file to 0777 now. So it should really work ... But still doesn't seem to. ! :/ I have no ideas now. Maybe the loop isn't working properly ?

Thanx for your help

Cheers

Chris

2

There are 2 answers

0
matwr On

Write permissions on the file are not sufficient you need write permissions on the directory itself to be able to delete a file within it.

You should first check the file exists, you should then check that you have the correct permissions on the directory NOT the file.

if(file_exists($file) && is_writeable(dirname($file))){
unlink($file);
}else{
//invalid path or permission problems
}
1
atxdba On
$file2 = chmod($file, 0777);

if(!unlink($file2)){

$file2 is getting the return value of chmod, which is a bool. You're then trying to unlink a true/false value. Perhaps you meant to unlink($file) ?

Edit to reflect your changes:

If $file is not a fully qualified path name $file will be relative to the current working directory of where ever the script is running from. Ensure $file is a full path name.