How to Read and Delete File From Folder Using PHP

In this short article, we are going to write a simple PHP script to unlink or delete one by one file from folder or directory. opendir method you can display all the files after you are delete one by one file. You may also like How to Read HTML From Text File Using PHP and How to create RSS Feed reader using PHP.

HTML or PHP Code

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

PHP Code

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

Leave a Reply

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