Delete a file from upload folder in PHP

 




How to delete a file from upload folder

 

coding-zonuploaded-file-delete-php

This tutorial teaches you how to delete a file/files from the specific folder using PHP.

Sometimes while deleting a record from database table, you also need to delete an image/file from the uploaded folder which is   associated to that record. 

For example, if you are removing a product from the table, at the same time, you also need to remove an uploaded product-image. So 

For this,

In PHP, there is a function called unlink().  Using unlink() function you can  remove a file from the specified folder.

Retrieve the product-image from database and pass it to unlink function along with full path.

 

Syn:

 
unlink("path_to_your_upload_directory/".filename_with_extension. );

ex


unlink("uploads/".$product_image );

Example Code

delete_product,php

 
<?php

$product_id = $_GET['pid']; 
 
$con  = mysqli_connect('localhost', 'root', '', 'productsdb');  
 
$SQL1 =  "SELECT FROM products WHERE product_id = $product_id"; 
 
$result1 = mysqli_query($con, $SQL1) ;
 
$row =  mysqli_fetch_assoc($result1) ;
 
$product_image  = $row['product_image'];
 
 
$SQL2 =  "DELETE FROM products WHERE product_id = $product_id";
 
$result2 = mysqli_query($con, $SQL2)or die(mysql_error());  
 
 
 
if($result2)
{
 
$product_image = 'uploads/'.$product_image ;
 
if (file_exists($product_image )) {
   
unlink($product_image );
 
echo "Product deleted";
 
 } 
 
}
 
...  

?>
 
 

 How to delete a given file from folder in PHP

 
example2: 
 
<?php

$filename = 'sample.txt';

if (unlink($filename)) { 
 
 echo 'The file' . $filename . 'deleted successfully!'
 
}  
 
else 
 
 
echo 'There was am error in deleting the file' . $filename
 
}
 
?> 

Comments

Popular posts from this blog

Using javascript pass form variables to iframe src

Creating a new PDF by Merging PDF documents using TCPDF

Import excel file into mysql in PHP