Aurora Aurora - 6 months ago 17
PHP Question

How do i delete an image in php?

I'm trying to delete an image in a ajax php file. I have the following code:

<?php
define('IS_AJAX', true);

$id = $db->real_escape_string($_GET['photo_id']);
$files = $db->query("SELECT * FROM uploaded_photos WHERE id=".$id);
$files = $files->fetch_object();

$file = $files->path;

if($file){
unlink("../uploads/".$file);
$db->query("DELETE FROM uploaded_photos WHERE id='".$id);

}


path, in this case, is the image e.g. 1.jpg. It does delete the table row, but it doesn't delete the image in the uploads folder. Hoping someone can help me on this. Thank you beforehand for your efford.

Answer

You may want to recheck your code. You have an unclosed Single Quote. See the Code below...

        define('IS_AJAX', true);

        $id     = $db->real_escape_string($_GET['photo_id']);
        $files  = $db->query("SELECT * FROM uploaded_photos WHERE id=".$id);
        $files  = $files->fetch_object();

        $file   = $files->path;

        // NOTE THAT if($file) WOULD ALMOST ALWAYS RETURN TRUE SO LONG AS IT CONTAINS ANY STRING
        // HOWEVER file_exists WILL CHECK IF THE FILE PHYSICALLY EXIST ON THE PATH/LOCATION OR NOT.
        // PREFER file_exists IN THIS SCENARIO INSTEAD.
        if(file_exists("../uploads/" . $file)){
            // CHANGE THE FILE PERMISSION ON THE IMAGE SO THAT YOU CAN WORK WITH IT...
            chmod("../uploads/" . $file, 0755);   // <== GIVES YOU PERMISSION TO DEAL WITH THE FILE...
            unlink("../uploads/".$file);
            // BY THE WAY;  HERE IS A PROBLEM... YOU HAVE AN UNCLOSED SINGLE QUOTE AFTER THE EQUAL SIGN.
            // I REALLY WONDER HOW THE TABLE ROW DELETES WITH THE TYPO...
            // TRY REMOVING OR COMPLETING IT THOUGH:        
            //$db->query("DELETE FROM uploaded_photos WHERE id='".$id);   <=== SEE THAT SINGLE QUOTE AFTER "=" THERE? THAT'S YOUR ENEMY.
            $db->query("DELETE FROM uploaded_photos WHERE id=".$id);
        }

UPDATE: WITHOUT COMMENTS

    <?php

        define('IS_AJAX', true);

        $id     = $db->real_escape_string($_GET['photo_id']);
        $files  = $db->query("SELECT * FROM uploaded_photos WHERE id='{$id}'" );
        $files  = $files->fetch_object();       
        $file   = $files->path;

        if(file_exists("../uploads/" . $file)){
            chmod("../uploads/" . $file, 0777); 
            unlink("../uploads/".$file);    
            $db->query("DELETE FROM uploaded_photos WHERE id='{$id}'");
        }
Comments