Search code examples
phpfile-uploadunlink

Unlink - Permission denied. How to resolve?


I want to delete a file using unlink but I receive a Warning Message,

Warning: unlink(uploads/487001/): Permission denied in

When I check on the folder, the file is successfully deleted. Below are the codes that I did,

Uploads.php

<?php
if (isset($_FILES['mc'])) {
    $file = $sno . "-" . date("Ymd") . "-" . $_FILES['mc']['name'];
    $file_loc = $_FILES['mc']['tmp_name'];
    $file_size = $_FILES['mc']['size'];
    $folder = "uploads/" . $sno . "/";
    $final_file = str_replace(' ', '-', strtolower($file));

    if ($file_size <= 0) {
        $error= "<span class=\"w3-text-red\">Select a file to upload</span>";
    }

    if (!is_dir($folder)) {
        mkdir($folder, 0777, true);
    }

    if (move_uploaded_file($file_location, $folder . $final_file)) {
        $upload = true; 
    }
}

Delete.php

<?php 
if(isset($_POST['delete'])){

    if(empty($_POST['checkbox'])){
        $error = "<span class=\"w3-container w3-text-red\">No data selected</span><p/>";
    } elseif(isset($_POST['checkbox'])){
        $checkbox = $_POST['checkbox'];
        $files = $_POST['file'];
        $path = 'uploads/' . $_SESSION['staff_no'] . '/';

        foreach ($files as $file) {
            if (file_exists($path.$file)) {
                chmod($path.$file, 0777);
                unlink($path.$file);
            } 
        }
    }

// Other validations & Delete row from database

This is the file structure,

Project Folder > Uploads > user_id > files

May I know what is the mistakes?


Solution

  • What does $POST['file'] is holding? If it is an array then check for blanks / null values as well. file_exists() will return true in case of $file is blank, but then your path will end up with uploads/487001/ and you will get that warning.