一注值得加入是爲了確保你的代碼不會產生這些圖像的「未經授權」的大小。
因此,下面的URL將創建圖像1234的200x200版本(如果尚不存在的話)。我會高度建議您確保請求的網址包含您支持的圖片尺寸。
/images/get/200x200/1234.jpg
有惡意的人可以先要求隨機網址,總是改變圖像的高度&寬度。這將導致您的服務器出現一些嚴重問題,它將坐在那裏,基本上處於受到攻擊的狀態,從而生成您不支持的尺寸圖像。
/images/get/0x1/1234.jpg
/images/get/0x2/1234.jpg
...
/images/get/0x9999999/1234.jpg
/images/get/1x1/1234.jpg
...
etc
這裏的代碼說明這是一個隨機剪斷:
<?php
$pathOnDisk = getImageDiskPath($_SERVER['REQUEST_URI']);
if(file_exists($pathOnDisk)) {
// send header with image mime type
echo file_get_contents($pathOnDisk);
exit;
} else {
$matches = array();
$ok = preg_match(
'/\/images\/get\/(\d+)x(\d+)\/(\w+)\.jpg/',
$_SERVER['REQUEST_URI'], $matches);
if(! $ok) {
// invalid url
handleInvalidRequest();
} else {
list(, $width, $height, $guid) = $matches;
// you should do this!
if(isSupportedSize($width, $height)) {
// size is supported. all good
// generate the resized image, save it & output it
} else {
// invalid size requested!!!
handleInvalidRequest();
}
}
}
// snip
function handleInvalidRequest() {
// do something w/ invalid request
// show a default graphic, log it etc
}
?>
不錯的建議,但... 如果通過上傳的新映像(通過管理界面)更改源,則會生成新的GUID,並且緩存的文件名將不再匹配。 圖像不應該與(s)FTP上傳,但我們都知道假設。 ;) 無論如何將看看實現。 – 2008-09-26 17:31:46
我還檢查圖像是否被緩存_after_對緩存腳本進行了任何修改,即if(filemtime($ cached_image)> filemtime($ _ SERVER ['SCRIPT_FILENAME'])){...}` – 2011-05-01 12:33:52