Read And Delete File From Folder Using PHP

Friday, Jan 27, 2017

Tags:- PHP


In this tutorial we will show you how to read and delete file from folder using PHP.Using this method you can display all the files present in folder and delete any type of file using PHP.You may also like create, edit and delete file using PHP.


Read And Delete File From Folder Using PHP


To Read And Delete File From Folder It Takes Only Two Steps:-

  1. Make a PHP file to read file from folder
  2. Make a PHP file to delete file from folder


Step 1.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>

In this step we read all the files from images folder and create a delete button for each file to delete that file from folder.We use opendir() function to open the folder for file reading and then use while() loop and readdir() function to read all the files and then we use closedir() function to close the directory.You may also like remove file extension using htaccess.



Step 2.Make a PHP file to delete file from folder

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

<?php
if(isset($_POST['delete_file']))
{
 $filename = $_POST['file_name'];
 unlink('images/'.$filename);
}
?>

In this step we get the file name and use php unlink() function to delete that file from folder.


That's all, this is how to read and delete file from folder using PHP.You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.

Join Us With Our 21000+ Subscribers And Get Our Latest Tutorials Update Via Email