从另一个网站目录获取PHP中的随机图像

时间:2013-11-07 19:46:16

标签: php

我有很多想要随机选择的图像,但是在免费托管下没有足够的空间来存储它们,所以我建了第二个网站来保存图像。

我已经尝试了glob命令,该命令适用于同一网站中的图像,但似乎没有从其他网站做任何事情。允许使用目录列表,通过输入url,我可以看到所有文件,但如果我运行代码则不返回任何内容。有没有人知道让它运作的方法?

代码在这里,回声部分是临时的

$images = glob('http://(mywebsite).com/images/*');
$randomImage = $images[rand(0, count($images) - 1)];
echo count($images);

2 个答案:

答案 0 :(得分:2)

此代码属于远程(图像)服务器端。我建议你在那里写一个rndimg.php种类,并插入这段代码,引用resp。文件系统当然。

然后,通过执行file_get_contents('http://imgserver/rndimg.php');或类似的操作,您可以每次都检索一个随机图像。

示例rndimg.php类似于:

$images = glob('*.png');
$randomImage = $images[rand(0, count($images) - 1)];
header('Content-Description: File Transfer');
header('Content-Type: image/png');
header('Content-Disposition: attachment; filename='.basename($randomImage));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($randomImage));
readfile($randomImage);
exit;

答案 1 :(得分:0)

不确定您是否真的了解http协议...您不能通过HTTP“dir”远程目录:您获得的内容始终是HTML响应。所以你可以做的是从远程获取Dir列表:

$page = file_get_contents('http://(mywebsite).com/images');

然后在$ page中解析文件中的HTML代码,例如

$matches = array();
$count = preg_match_all('/\<a href=\"([^\"]+)\"\>/',$page,$m);
foreach($matches[1] as $file) {
    $img = file_get_contents('http://(mywebsite).com/images/'.$file);
}

并处理图像。