我有一個照片共享應用程序,我用timthumb來顯示縮略圖。當用戶刪除照片時,我希望緩存的圖像也從timthumb的緩存目錄中刪除以節省空間。目前我只能從緩存中刪除所有文件,但這並不理想。如何從timthumb的緩存中刪除特定的文件?
如何從timthumb的緩存中只給定原始圖像的特定文件?
我有一個照片共享應用程序,我用timthumb來顯示縮略圖。當用戶刪除照片時,我希望緩存的圖像也從timthumb的緩存目錄中刪除以節省空間。目前我只能從緩存中刪除所有文件,但這並不理想。如何從timthumb的緩存中刪除特定的文件?
如何從timthumb的緩存中只給定原始圖像的特定文件?
我來到這個解決方案。我必須對timthumb.php
文件做一些修改,以便我可以包含該文件並從另一個文件實例化該類。
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;
}
}
現在,我可以得到一個給定的圖像緩存文件名並刪除它。代碼並不漂亮,但我需要節省空間。
delete_cache.php:
我們需要的第一件事是cacheDirectory = './cache'
:我們要刪除本地圖像的緩存文件
<?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);
}
asuming 秒,FILE_CACHE_PREFIX = 'timthumb'
那麼它是內部的(_int_)
再有就是一個MD5哈希:
和最後,FILE_CACHE_SUFFIX = '.timthumb.txt'
例如:
HTML:
<img src='timthumb.php?src=images/example.png&w=150'>
PHP :
$cachefile = 'cache/timthumb_int_'.md5(filemtime('timthumb.php') . '-' . fileinode('timthumb.php') . filemtime("images/example.png"). "src=images/example.png&w=150" . 1) . '.timthumb.txt';
unlink($cachefile);