Search code examples
phptimthumb

How to delete specific files from timthumb's cache?


I have a photo sharing app and I use timthumb to display the thumbnails. When a user delete a photo, I want the cached images also deleted from the timthumb's cache directory to save space. Currently I can only delete all files from cache, but it is less than ideal.

How to delete only specific files from timthumb's cache given the original image?


Solution

  • I came to this solution. I have to make little modifications to the timthumb.php file so I can include the file and instantiate the class from another file.

    timthumb.php:

    <?php
    
    // If this file is included from other script, don't start timthumb
    if (basename($_SERVER['SCRIPT_NAME']) == basename(__FILE__)) {
      timthumb::start();
    }
    
    class timthumb {
      ...
      // $cachefile is protected so I create a getter function
      public function getCacheFile() {
        return $this->cachefile;
      }
    }
    

    Now I can get the cache filename for a given image and delete it. The code is not pretty, but I need to save space.

    delete_cache.php:

    <?php
    require 'timthumb.php';
    
    // Fake the query string
    $_SERVER['QUERY_STRING'] = 'src=path/to/src/image.jpg&w=200&h=150';
    parse_str($_SERVER['QUERY_STRING'], $_GET);
    
    // When instantiated, timthumb will generate some properties: 
    // salt, directories, cachefile, etc.
    $t = new timthumb();
    
    // Get the cache file name
    $f = $t->getCacheFile();
    
    // Delete the file
    if (file_exists($f)) {
        unlink($f);
    }