Search code examples
phpmysqlunlink

My Image is not removing from folder


I am trying to remove images from image folder and database. In my script it delete image from database but it is not removing from the image folder.

This is my CODE so far:

if ((isset($_POST['imageId'])) && (is_numeric($_POST['imageId'])) ) { // Form submission.
    $imageId = (int)$_POST['imageId'];

    // fetch the selected images to delete
    $query = " SELECT image_id, member_id, image
                         FROM  image_info
                         WHERE image_id = ?";

    $stmt = $mysqli->prepare($query);

    if ($stmt) {
        $stmt->bind_param('i', $imageId);  
        $stmt->execute();    
        $stmt->store_result();
        $numrows = $stmt->num_rows;

        if ($numrows == 1) {
            $stmt->bind_result($image_id, $member_id, $image);

            // define constant for upload folder
            //define('UPLOAD_DIR_2', "images/slider/$member_id");   

            // Fetch all the records:
        while ($stmt->fetch()) {
            if(file_exists("images/slider/$member_id/".$image)) {
                unlink("images/slider/$member_id/". $image); // delete file from folder
                //echo UPLOAD_DIR_2;
            } elseif(is_dir($image)) {
                rmdir($image); // or system("rm -rf " . escapeshellarg($dir)); 
            }
        }               

            // Make the delete query:
            $q = 'DELETE FROM image_info WHERE image_id= ? LIMIT 1'; 
            $stmt = $mysqli->prepare($q);
            $stmt->bind_param('i', $imageId);

            // Execute the query:
            $stmt->execute();

            if ($stmt->affected_rows == 1) {
                $success = "The slideshow image Deleted successfully.";
                echo $successAlert;
            }   
            $stmt->close();
            unset($stmt);
        }
    }
} 

Can anybody tell me what is wrong with this? Hope somebody may help me out.

Thank you.


Solution

  • please try like this,

    $path = $_SERVER['DOCUMENT_ROOT']."/images/slider/".$member_id."/".$image;
    unlink($path);
    

    UPDATED:

    $path = dirname($_SERVER["SCRIPT_FILENAME"])."/images/slider/".$member_id."/".$image;
        unlink($path);