Click here to Skip to main content
15,886,963 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
How can i delete an image from folder images when i dont know the name of the image?
I have a project when in the admin page you can upload and delete images.
But my delete file only deletes images path from the database, how can i also delete the image itself from the folder?
Below is my code.
Thank you.

What I have tried:

<?php
  include("connect.php");

	$id =$_REQUEST['id'];


	// sending query
	mysqli_query($conn ,"DELETE FROM images WHERE id = '$id'")
	or die(mysqli_error());

  mysqli_query($conn ,"DELETE FROM profile_image WHERE id = '$id'")
	or die(mysqli_error());

  $name = mysqli_query($conn ,"SELECT * FROM images WHERE id = '$id'")
	or die(mysqli_error());

  $row= mysqli_fetch_array($name);
  $r = $row['image'];

  $path = "admin/images/$r";
  if(!unlink($path))
  {
    echo "Not Working";
  }
  else {
    header("Location: images.php?working");
  }


	header("Location: images.php");
?>
Posted
Updated 19-Jun-19 8:45am

1 solution

Quote:
delete file only deletes images path from the database
Before you execute this command, you need to delete the file from the web server too. At this moment you do have the file path, so just pass that to the PHP function that deletes the file. I would suggest doing this first,
PHP
$path = "admin/images/$r";
if(!unlink($path))
{
    echo "Not Working";
}
else {
    // execute the command from database now.
}
Once this line has been executed you lose the file path and you can no longer delete the file—unless you delete everything from the directory, or you capture it from your database backups; or an even stupid solution or deleting everything that doesn't have a link in the database, too bad of a solution!

PHP: unlink - Manual[^]
 
Share this answer
 
Comments
simple world 19-Jun-19 15:03pm    
Hello thank you for replying.
I did what you said.
And this is the result.
unlink(admin/images/50.jpg): No such file or directory in /opt/lampp/htdocs/test/admin/delete.php on line 20
Not Working
I get error and the funny thing is that the path is correct.
What might be the problem?
simple world 19-Jun-19 15:05pm    
Hey sorry the path was incorrect.
I fixed it and it worked great.
Thank you very much.
I accepted you answer as solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900