餅乾工坊

完整版: [PHP]隨機圖片
您正在瀏覽簡化版內容。 請點這裡瀏覽完整版。
隨機圖片,可以用在隨機背景 Logo 頭像 ...etc
程式碼:
<?php
$path='.';
$files=array();
if ($handle=opendir("$path")) {
while(false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(substr($file,-3)=='gif' || substr($file,-3)=='jpg' || substr($file,-3)=='png') $files[count($files)] = $file;
}
}
}
closedir($handle);

$random=rand(0,count($files)-1);
if(substr($files[$random],-3)=='gif') header("Content-type: image/gif");
elseif(substr($files[$random],-3)=='jpg') header("Content-type: image/jpeg");
elseif(substr($files[$random],-3)=='png') header("Content-type: image/png");
readfile("$path/$files[$random]");
?>
由於這是 php ,如果用在隨機頭像會有 php 格式不符的限制
但可以搭配 .htaccess
程式碼:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*).jpg$ $1.php
RewriteRule ^(.*).png$ $1.php
RewriteRule ^(.*).gif$ $1.php
</IfModule>
註:這個 .htaccess 可以用在特定某些檔案的防盜連

如果php後面有參數才需要改成下面這樣
RewriteRule ^(.*).jpg$ $1.php?$2