How to delete a file using PHP?

how to delete a file using php?

How to delete a file using PHP? In this instructional exercise we will tell you the best way to peruse and erase document from organizer utilizing PHP. Using this strategy you can show every one of the records present in envelope and erase any kind of record utilizing PHP. You may likewise like make, alter and erase document utilizing PHP.

To erase a record by utilizing PHP is extremely simple. Erasing a record implies totally eradicate a document from a registry so the document is never again exist. PHP has an unlink() work that permits to erase a record. The PHP unlink() work takes two boundaries $filename and $context.

Syntax:

unlink( $filename, $context );

Program 1: This program utilizes unlink() capacity to eliminate document from index.

Assume there is a record named as “gfg.txt”

<?php
// PHP program to delete a file named gfg.txt 
// using unlike() function 
  
$file_pointer = "gfg.txt"
  
// Use unlink() function to delete a file 
if (!unlink($file_pointer)) { 
    echo ("$file_pointer cannot be deleted due to an error"); 
else
    echo ("$file_pointer has been deleted"); 
 
?> 

Output:

gfg.txt has been deleted

Program 2: This program utilizes unlink() capacity to erase a record from envelope subsequent to utilizing some activity.

<?php
// PHP program to delete a file named gfg.txt 
// using unlike() function 
 
$file_pointer = fopen('gfg.txt', 'w+'); 
   
// writing on a file named gfg.txt 
fwrite($file_pointer, 'A computer science portal for geeks!'); 
fclose($file_pointer);   
 
// Use unlink() function to delete a file 
if (!unlink($file_pointer)) { 
    echo ("$file_pointer cannot be deleted due to an error"); 
else
    echo ("$file_pointer has been deleted"); 
  
?> 

Output:

Warning: unlink() expects parameter 1 to be a valid path, resource
given in C:\xampp\htdocs\server.php on line 12
Resource id #3 cannot be deleted due to an error

Note: If the record doesn’t exist then it will show a mistake.

PHP is a server-side prearranging language planned explicitly for web improvement. You can gain PHP from the beginning by following this PHP Tutorial and PHP Examples.

Make a PHP file to read file from folder

We make a PHP file and save it with a name read.php

<html>
<body>
<div id="wrapper">

<div id="file_div">
<?php
$folder = "images/";
if ($dir = opendir($folder))
{
 while (($file = readdir($dir)) !== false)
 {
  echo "<p>".$file."</p>";
  echo "<form method='post' action='delete_file.php'>";
  echo "<input type='hidden' name='file_name' value='".$file."'>";
  echo "<input type='submit' name='delete_file' value='Delete File'>";
  echo "</form>";
 }
 closedir($dir);
}
?>
</div>

</div>
</body>
</html>

Also Read: How to Install OpenCV for Python on Windows?

Leave a Reply

Your email address will not be published. Required fields are marked *