Delete selected files php

This tutorial explains how to delete selected files php. This example read the files from the upload folder .Then it displays all files in tables as shown below.

There is a checkbox next to each file.On the button submit it goes through the checkbox array and delete the selected files.


Step by step explanation

  1. Read Files
  2. Delete Selected Files

Read Files

This section reads all the files in the upload folder.Then it list all the files the folder.

 public function readFiles() {
        $thelist = '';
        if ($handle = opendir('upload/')) {
            $thelist .= '<form method="post"><table>';
            $thelist .= '<tr><th colspan="2" align="left"><h2>List all files</h2></th></tr>';
            while (false !== ($file = readdir($handle)))
                   if ($file != "." && $file != "..")
                         $thelist .= '<tr><td><input type="checkbox" name="selectedFiles[]" value="'.$file.'"></td><td><a href="'.$file.'">'.$file.'</a></td></tr>';
                $thelist .=  '<tr><td colspan="2" align="left"><input type="submit" value="Delete selected files" name="delete" style="height:30px;width:150px; margin-top:8px;"></td></tr>';
                $thelist .= '</table></form>';
        echo $thelist;

Delete Selected Files

On the button submit it retrieve all the files from the checkbox array.The foreach loop it iterate through the array and delete the selected file if that exists.

  public function selectedFiles() {
         if(isset($_REQUEST['delete'])) {
            if( sizeof( $_POST['selectedFiles'] ) > 0) {              
                $this->deleteFiles( $_POST['selectedFiles'] );
    public function deleteFiles($selectedFiles) {
        foreach( $selectedFiles  as $selectedFile ) {
            $path= "upload/".$selectedFile;
            if (file_exists($path)) {
                if( unlink( $path ) ) 
                    echo "Deleted file " .$selectedFile."\n";
            else {
                echo "The file $path does not exist";

If you have any further queries please leave a reply.

Share this Tutorial

Leave a Reply

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