JS · jQuery · PHPMar 20, 2012 · 3 min read

List and Delete Files with jQuery, JSON, PHP

How to build a file cache viewer and cleaner: PHP reads a directory and returns JSON, jQuery renders the list, and a second PHP script deletes everything. A practical example of client-server JSON exchange.

I recently implemented functionality that would dynamically generate image files. As images are generated, they are cached on the server. As the cache grows, the user would have the option to view the files in the cache, and delete them all.

This tutorial will explain the interaction between the client and the server, how files within a directory can be read and deleted, and how to handle packaging and interpreting JSON responses with PHP and jQuery.

Returning a JSON-formatted List of Files with PHP

I have a trigger on the page that will retrieve the files and output them into a list, which starts off empty:
HTML
View Cache
Clear Cache

I bind the button to an ajax call to the following PHP page, which returns a JSON object:

PHP
if ($handle = opendir('cache')) {
  $files = array();
  while (false !== ($entry = readdir($handle))) {
    if ($entry != "." && $entry != "..") 
      array_push($files, $entry);
  }

echo json_encode($files);

closedir($handle);
}

Here, we open a directory, iterate through it, and for each file in the directory we append it to an array called $files. Using json_encode(), we automatically create a string that wraps each filename in quotes, separates the filenames with commas, and adds the […] around the array.

Displaying the JSON with jQuery

I named the page viewcache.php, and call it using with a little jQuery ajax:
JavaScript
$('#view-btn').click( function() {
  $.post(
    "viewcache.php",
    function(data){
      $(data).each( function(){
        //for each item in the JSON array, do this...
      });
    },
    'json'
  );
});

This will call the PHP page that returns the contents of a directory, and the 'json' argument tells us that the response is in JSON format. The entire response is in a javascript array called data; if we turn the data array into a jQuery object, we can use the each() method to iterate over it.

In the each() function, this refers to each element in the array; in our case, it's the name of the file in our cache. We can append our files into the empty list we created earlier:

JavaScript
$('#cache').append(''+this+'');

Removing Files with PHP

Files can be removed using the unlink(); function. I created a PHP file called clearcache.php that deletes every file in the cache.
PHP
if ($handle = opendir('cache')) {
  while (false !== ($entry = readdir($handle)))
    if ($entry != "." && $entry != "..")
      unlink('cache/'.$entry);

closedir($handle);
}

readdir() just gets the filename for the path specified in opendir(). Note that we will need to append the path to the filename when using unlink().

Invoking the Delete Script

We can bind the clear-btn to invoke the following ajax call:
JavaScript
$('#clear-btn').click( function() {
  $.ajax({
    url: 'clearcache.php',
    success: function() {
      $('#cache li').remove();
    }
  });
});

This will call clearcache.php, which deletes the files in our cache; after the delete script has been run, its a good idea to let the user know the files have been deleted by removing them from view, which is why we should iterate over each list-item and remove them from the DOM.