delete image from folder in php and MySQL Database

Hi, today We are going to tell you about delete image from folder in php how to remove the file or picture from folder as well as MySQL database Table using php script, many developers they are not care to delete a picture or file while deleting a records from database they keep the files related to records and it will effects on server storage, we will find many solutions to remove files from directory We will give you a simple process let’s display how we do this.

As a PHP beginner step by step, remove file from folder as well as database can be very hard. Because it required Two types of the processes. First of all is remove file from directory. Second is delete database record having that file path.

PHP Remove File from Folder and Database

Developer often confused which process comes starting. few delete database record initial and then remove/delete file from directory as well as many remove/delete file primary and then delete database record. Therefor which practice is correct?

Best solutions is to remove/delete file from directory first(delete uploaded file php) and then delete MySQL database table record by php delete image on click. In this tutorial We are going to Display you php unlink image from folder with how to do that.

delete image from folder in php
jQuery AJAX Add Delete Multiple Image Upload

Create Database:

here simple step to DB connect this file to mysql database as well as get or fetch the records from gallery DB table bellow We are just getting single record only if you want you can retrieve all Database records and keep it in while loop, now We are just location the image tag as well take the src anchor tag for delete button as well as location the do_file_delete.php file in href with We just pass arguments the gallery id to customproductid variable

Also Read This ๐Ÿ‘‰   How to change content with next and previous button?

Create database demo;

Create Database Table:


CREATE TABLE `galleries` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`image` VARCHAR(255) NOT NULL,
`created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
success KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=10
;

Database Connection and Select Images Query:



$conn = mysqli_connect('localhost','root','','gallery_demo');

	if(!$conn)
	{
		die(mysqli_error());
	}
	
	
	$sql = "select * from galleries";
	$rs = mysqli_query($conn, $sql);


Display Images from Database:


<div class="container">
		<h3 class="text-center">Delete Images</h3>
		
		<div class="row">

<?php 
		while($row = mysqli_fetch_assoc($rs))
		{
			$galleryImgPathW = "uploads/".$row['image'];
		?>	
			
				
			<div class="col-md-12 text-center" style="margin-top:10px">
				<img src="<?php echo $galleryImgPathW ?>" width="200">
				<a href="?deleteid=<?php echo $row["id"]?>" class="btn btn-primary">Delete</a>
			</div>
			
			
	<?php		
		}
		
	?>
	</div>
	</div>


</div>
</div>

Success and Error Messages:



<?php 
		if(isset($displayErrMessage))
		{
		?>
			<div class="alert alert-danger">
				<?php 
					echo $displayErrMessage;
					unset($displayErrMessage);
				?>
			</div>
		<?php 
		}
		?>
		
		<?php 
		if(isset($_GET['success']) && $_GET['success'] == 'true')
		{
		?>
			<div class="alert alert-success">
				<?php 
					echo "Images has been deleted sucessfully";
				?>
			</div>
		<?php 
		}
		?>


Remove/delete Image Code:

here connect this file to database, now retrieve the image from gallery table by using where query condition and assign the $del variable to galleryid, now use unlink() method to remove/delete the files or pictures from folder unlink(“medias/$fetchImgTitleName”); inside the function just give the directory path and file name to remove/delete after the function write the query to delete the gallery record with delete previous image from directory when updated by new image in php also you can read my previous post Like as how to delete image from folder in php codeigniter



<?php 
if(isset($_GET['deleteid']))
	{
		$querySelect = "select * from galleries where id = ".$_GET['deleteid'];
		$ResultSelectStmt = mysqli_query($conn,$querySelect);
		$fetchRecords = mysqli_fetch_assoc($ResultSelectStmt);
		
		$fetchImgTitleName = $fetchRecords['image'];
		
		$createDeletePath = "uploads/".$fetchImgTitleName;
		
		if(unlink($createDeletePath))
		{
			$liveSqlQQ = "delete from galleries where id = ".$fetchRecords['id'];
			$rsDelete = mysqli_query($conn, $liveSqlQQ);	
			
			if($rsDelete)
			{
				header('location:index.php?success=true');
				exit();
			}
		}
		else
		{
			$displayErrMessage = "Unable to delete Image";
		}
		
	}
?>


Complete Code : delete image from database and folder in php

delete file from folder in php



<?php 
	
	$conn = mysqli_connect('localhost','root','','galleries_demo');

	if(!$conn)
	{
		die(mysqli_error());
	}
	
	
	$sql = "select * from galleries";
	$rs = mysqli_query($conn, $sql);
	
	
	if(isset($_GET['deleteid']))
	{
		$querySelect = "select * from galleries where id = ".$_GET['deleteid'];
		$ResultSelectStmt = mysqli_query($conn,$querySelect);
		$fetchRecords = mysqli_fetch_assoc($ResultSelectStmt);
		
		$fetchImgTitleName = $fetchRecords['image'];
		
		$createDeletePath = "uploads/".$fetchImgTitleName;
		
		if(unlink($createDeletePath))
		{
			$liveSqlQQ = "delete from galleries where id = ".$fetchRecords['id'];
			$rsDelete = mysqli_query($conn, $liveSqlQQ);	
			
			if($rsDelete)
			{
				header('location:index.php?success=true');
				exit();
			}
		}
		else
		{
			$displayErrMessage = "Sorry, Unable to delete Image";
		}
		
	}

	
?>

<!DOCTYPE html>
<html>
<head>
<title>PHP remove uploaded file from folder and database - www.pakainfo.com</title>


<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >


<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" >
</head>

<body>
	<div class="container">
		<h3 class="text-center">Delete gallery Images</h3>
		
		<div class="row">
		
		<?php 
		if(isset($displayErrMessage))
		{
		?>
			<div class="alert alert-danger">
				<?php 
					echo $displayErrMessage;
					unset($displayErrMessage);
				?>
			</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))
		{
			$galleryImgPathW = "uploads/".$row['image'];
		?>	
			
				
			<div class="col-md-12 text-center" style="margin-top:10px">
				<img src="<?php echo $galleryImgPathW ?>" width="200">
				<a href="?deleteid=<?php echo $row["id"]?>" class="btn btn-primary">Delete</a>
			</div>
			
			
	<?php		
		}
		
	?>
	</div>
	</div>
	
	
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>	
</body>
</html>

How to delete image from folder in PHP?

To delete an image from a folder in PHP, you can use the unlink() function. The unlink() function is used to delete a file in PHP. Here’s an example code snippet that demonstrates how to delete an image file:

Also Read This ๐Ÿ‘‰   PHP Calculate Difference Between Two Dates

$filename = 'path/to/image.jpg';

if (file_exists($filename)) {
    unlink($filename);
    echo "File deleted successfully.";
} else {
    echo "File not found.";
}


In this example, we first set the $filename variable to the path of the image file we want to delete. We then use the file_exists() function to check if the file exists before deleting it. If the file exists, we call the unlink() function to delete the file, and we output a success message. If the file does not exist, we output a message indicating that the file was not found.

Note that the unlink() function will permanently delete the file from the file system, so use it with caution. Also, make sure that you have the necessary permissions to delete the file.

Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about delete image from folder in php.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, donโ€™t forget to share.