image.php代码部分:(请忽略博客代码类型标识的错误)

<?php
$dir = './images/';
$list = scandir($dir,0);
$rand = rand(2,count($list)-'1');
$file = $dir.$list[$rand];
header("Location:{$file}");
/**
//方法2,直接输出
$info = @getimagesize($file);
$mime = $info["mime"];
if($mime == "image/png")
{
	header("Content-Type:image/png");
}
elseif($mime == "image/jpeg")
{
	header("Content-Type:image/jpeg");
}
elseif($mime == "image/gif")
{
	header("Content-Type:image/gif");
}
elseif($mime == "image/vnd.wap.wbmp")
{
	header("Content-Type:image/vnd.wap.wbmp");
}
elseif($mime == "image/x-xbitmap")
{
	header("Content-Type:image/x-xbitmap");
}
elseif($mime == "image/webp")
{
	header("Content-Type:image/webp");
}
elseif($mime == "image/bmp")
{
	header("Content-Type:image/bmp");
}
else
{
	header("Content-Type:image/png");
}
echo file_get_contents($file);
*/
?>

1.去方法2和结束标识'?>'

<?php
$dir = './images/';
$list = scandir($dir,0);
$rand = rand(2,count($list)-'1');
$file = $dir.$list[$rand];
header("Location:{$file}");

2.去变量

去变量$dir

<?php
$list = scandir('./images/',0);
$rand = rand(2,count($list)-'1');
$file = './images/'.$list[$rand];
header("Location:{$file}");

去变量$file

<?php
$list = scandir('./images/',0);
$rand = rand(2,count($list)-'1');
header('Location:./images/'.$list[$rand]);

去变量$rand

<?php
$list = scandir('./images/',0);
header('Location:./images/'.$list[rand(2,count($list)-'1')]);

3.精简变量和函数(省略换行,'<?php'后紧跟' '(空格))

<?php $l = scandir('./images/',0);header('Location:./images/'.$l[rand(2,count($l)-'1')]);

合并$l到header(不推荐),会导致遍历两遍目录(两倍的时间花费)

<?php header('Location:./images/'.scandir('./images/')[rand(2,count(scandir('./images/'))-'1')]);

最终结果:

<?php $l=scandir('./images/');header('Location:./images/'.$l[rand(2,count($l)-'1')]);

共只有1行,第一行开始是PHP标签和变量$l,遍历目录,然后是重定向,复合了数组抽取随机键(数组的键0和1的值分别是'.'和'..',因此随机数从2开始,而最大值-'1'(减1)是因为数组是从0开始的)

相关项目:

https://github.com/xiwangly2/php_img_spider


本当の声を響かせてよ