Question:
Delete an image using PHP?
Johnies
2009-07-06 04:30:58 UTC
I have a folder images/ i've created a php script that uploads the image and now i want to delete it. I have in the form that deletes the image a that takes a value of the image's path to be deleted. I've tried the unlink function but still nothing. I was thinking of writing sth like unlink($_POST[img_del]); HELP???
Three answers:
anonymous
2009-07-06 04:36:46 UTC
First add the next function to your file:

function delete_images_by_refnum($image_folder, $ref_num)

{

$d = opendir($image_folder);'

if(!is_resource($d)) return;

while($f = readdir($d))

{

if(substr($f, 0, strlen($ref_num)+1) == $ref_num + '_')

unlink ($image_folder.'/'.$f);

}

}



Secondly edit the code you quotes in your last post to call the function:



if ($row = mysql_fetch_array($PropertiesResult))

{

$ref_num = $row['property_ref_num'];

delete_images_by_refnum(dirname(__FILE__).'/myimagefolder', $ref_num);



You have to change the first argument to state the correct foldername offcourse. You have to provide a relative link to the file this code is in. So when your code is in lib/delete.php and your images are in img/ the command would be:

delete_images_by_refnum(dirname(__FILE__).'/../img', $ref_num);
just "JR"
2009-07-06 05:31:25 UTC
To use unlink, you must be IN the relevant diretory. (You cannot delete a file passing a PATH).

// Read your post to have image name:

$image = $_POST['img_del']; // (or $_GET)

// get the current directory:

$curdir = getcwd();

// Change to the directory where the image is:

chdir("images/");

// delete the image

unlink ($image); // must be full name with extention!

// return to the original directory:

chdir($curdir);
bustin98
2009-07-07 07:10:06 UTC
Man, what is it with making things harder than it needs to be?



First: you need the path of the directory:



$dir = 'd:/my_folder/';



Then you need the name of the image:



$img = 'image.jpg';



Now this:



$fileName = $dir.$img;



if(file_exists($fileName)) unlink($fileName);



Check to make sure the file exists before deleting it. You can alter it so if the conditional statement fails you can get an error message.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...