简体   繁体   中英

deleting image from the storage folder in php

I want to delete the image from the storage folder at the time of deleting from the database also.

The image file is getting deleted from database but unable to delete from server storage folder.

The image is getting stored in http://url.com/foldername/files/newsletter

The below is the code i used..

<?php

$id = intval($_REQUEST['id']);

include 'db/connection.php';



$sql1 = mysql_query("select * from tablename where id=$id");
$results=mysql_fetch_array($sql1);

if($results["file"]!="") {  
    $image=$results["file"];
    unlink("../files/newsletter/".$image);
    }



$sql = "delete from tablename where id=$id";

$result = @mysql_query($sql);


if ($result){
    echo json_encode(array('success'=>true));
} else {
    echo json_encode(array('msg'=>'Some errors occured.'));
}

?>

Plz help in resolving..Thank you

try to add document root with your code to something like code below.

$imageWithPath = $_SERVER['DOCUMENT_ROOT']."/files/newsletter/".$image;
@unlink($imageWithPath);

Can you print out what your $results["file"] value is and check.

You are using mysql_fetch_array it should be inside while loop

$sql1 = mysql_query("select * from tablename where id=$id");
while($row = mysql_fetch_array($sql1)){
    $image = $row["file"];
    //make sure below path is correct.
    $image_path = $_SERVER['DOCUMENT_ROOT'].'/foldername/files/newsletter/'.$image;
    echo $image_path;//you can compare if the path is correct or not
    //Also check if file exists here
    if(file_exists(image_path)){
       unlink($image_path);
    }
    else{
      echo 'file doesnot exist';
    }
}

Also you will need to have permissions to be able to delete the file. Make sure the apache or user that runs your script file have correct permission or ownership of the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM