9.4 C
Munich
Friday, March 24, 2023

Delete Image from folder in PHP

Must read

In this article, you going to see how to delete image from the folder in PHP and also from the database in a detailed step by step with a simple example.

If you are looking for this topic then you are at a right place.

Before going to start with the topic, make sure that you have a database with a table which consist of image.

If not then create the table and add some image into to database with the name of image as that in the folder section called “imageupload“.

Below is SQL Code snippet to create table in database.

-- Table structure for table `images`
CREATE TABLE `images` (
  `id` int(11) NOT NULL,
  `image` varchar(255) NOT NULL,
  `created` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Then insert some images with the help of insert query with the same name as that image name in folder section which we have to delete.

Let’s start with the topic of Delete Image from folder in PHP.

To delete the image from the folder and also from the database, make sure regarding the configuration section for the database connection.

With the help of the database connection only all the image get display from database which we have to delete.

Below to code snippet for the database connection.

<?php 
   /* database configuaration */
   define('DB_SERVER', 'localhost');
   define('DB_USERNAME', 'root');
   define('DB_PASSWORD', '');
   define('DB_DATABASE', 'phpimagetutorial');
   $con  = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);

   // Check connection
	if (mysqli_connect_errno()) {
	  echo "Failed to connect to MySQL: " . mysqli_connect_errno();
	  exit();
	}
?>

Above code snippet add to root folder and save in a file called as config.php file.

To fetch the record from the database you have to include the config file in top section.

After including config file in top section there is not necessary pass the detail for database connection again and again.

To fetch all the image record from the database execute the select SQL query to get all the record of image.

Then with the help of while loop and mysqli_fetch_assoc function display all the image.

And in that add an anchor tag into it and add in its href id of image so that when you click on the anchor tag as button delete, it will send the id of image.

This ID of image is get checked and if its present in the database then its get deleted from the database and also from the folder.

To delete from folder use unlink function in which folder path is passed as a parameter.

Below is the code snippet for how the data get fetch and delete from the folder using unlink function.

<?php 
	include("config.php");
	$sql = "select * from images";
	$rs = mysqli_query($con, $sql);
	if(isset($_GET['deleteid']))
	{
		$selectSql = "select * from images where id = ".$_GET['deleteid'];
		$rsSelect = mysqli_query($con,$selectSql);
		$getRow = mysqli_fetch_assoc($rsSelect);
		
		$getIamgeName = $getRow['image'];
		
		$createDeletePath = "imageuploads/".$getIamgeName;
		
		if(unlink($createDeletePath))
		{
			$deleteSql = "delete from images where id = ".$getRow['id'];
			$rsDelete = mysqli_query($con, $deleteSql);	
			
			if($rsDelete)
			{
				header('location:index.php?success=true');
				exit();
			}
		}
		else
		{
			$errorMsg = "Unable to delete Image";
		}
	}
?>

Layout of delete images code snippet given below.

<div class="container">
	<h2 class="text-center">Please click on Delete Button to - Delete Images </h2>
	<div class="row">
	<?php 
	if(isset($errorMsg))
	{
	?>
		<div class="alert alert-danger">
			<?php 
				echo $errorMsg;
				unset($errorMsg);
			?>
		</div>
	<?php 
	}
	?>
	<?php 
	if(isset($_GET['success']) && $_GET['success'] == 'true')
	{
	?>
		<div class="alert alert-success">
			<?php 
				echo "Images has been deleted sucessfully";
			?>
		</div>
	<?php 
	}
	?>
<?php 
	while($row = mysqli_fetch_assoc($rs))
	{
		$imgWithPath = "imageuploads/".$row['image'];
	?>		
		<div class="col-md-12 text-center" style="margin-top:10px;">
			<img src="<?php echo $imgWithPath ?>" width="200">
			<a href="?deleteid=<?php echo $row["id"]?>" class="delBtn"
			>Delete</a>
		</div>	
<?php		
	}
?>
</div>
</div>	

CSS code snippet for delete images display

.container{
	margin:0 auto;
	border:10px solid #1ABC9C;
	width:50%;
	text-align:center;
	verticle-align:middle;
	padding:20px;
	border-radius:10px;
	background-color:#1ABC9C;
}
h2{
	color:#ffffff;
}
.delBtn{
	padding:10px;
	color:white;
	border-radius:5px;
	background-color:#C70000;
}

Below is complete code snippet for delete Image from folder in PHP

<?php 
	include("config.php");
	$sql = "select * from images";
	$rs = mysqli_query($con, $sql);
	if(isset($_GET['deleteid']))
	{
		$selectSql = "select * from images where id = ".$_GET['deleteid'];
		$rsSelect = mysqli_query($con,$selectSql);
		$getRow = mysqli_fetch_assoc($rsSelect);
		
		$getIamgeName = $getRow['image'];
		
		$createDeletePath = "imageuploads/".$getIamgeName;
		
		if(unlink($createDeletePath))
		{
			$deleteSql = "delete from images where id = ".$getRow['id'];
			$rsDelete = mysqli_query($con, $deleteSql);	
			
			if($rsDelete)
			{
				header('location:index.php?success=true');
				exit();
			}
		}
		else
		{
			$errorMsg = "Unable to delete Image";
		}
	}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP remove uploaded file from folder and database</title>
</head>
<style>
	.container{
		margin:0 auto;
		border:10px solid #1ABC9C;
		width:50%;
		text-align:center;
		verticle-align:middle;
		padding:20px;
		border-radius:10px;
		background-color:#1ABC9C;
	}
	h2{
		color:#ffffff;
	}
	.delBtn{
		padding:10px;
		color:white;
		border-radius:5px;
		background-color:#C70000;
	}
</style>
<body>
	<div class="container">
		<h2 class="text-center">Please click on Delete Button to - Delete Images </h2>
		<div class="row">
		<?php 
		if(isset($errorMsg))
		{
		?>
			<div class="alert alert-danger">
				<?php 
					echo $errorMsg;
					unset($errorMsg);
				?>
			</div>
		<?php 
		}
		?>
		<?php 
		if(isset($_GET['success']) && $_GET['success'] == 'true')
		{
		?>
			<div class="alert alert-success">
				<?php 
					echo "Images has been deleted sucessfully";
				?>
			</div>
		<?php 
		}
		?>
	<?php 
		while($row = mysqli_fetch_assoc($rs))
		{
			$imgWithPath = "imageuploads/".$row['image'];
		?>		
			<div class="col-md-12 text-center" style="margin-top:10px;">
				<img src="<?php echo $imgWithPath ?>" width="200">
				<a href="?deleteid=<?php echo $row["id"]?>" class="delBtn"
				>Delete</a>
			</div>	
	<?php		
		}
	?>
	</div>
	</div>	
</body>
</html>

Output :

Delete Images from folder and Database
Delete Images from folder and Database

Upload multiple images in PHP and store in database

Conclusion :

Finally, we have done with discussion regarding delete Image from folder in PHP.

I hope you like this article and if you feel like we missed out on anything, please comment below.

- Advertisement -spot_img

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisement -spot_img

Latest article