【问题标题】:Pulling Random Images From A Folder Above The public_html Folder从 public_html 文件夹上方的文件夹中提取随机图像
【发布时间】:2013-07-19 20:51:11
【问题描述】:

所以我用这段代码创建了一个 image.php 文件并将它放在我的 public_html 文件夹中:

<?php
header('Content-Type: image/jpeg');
readfile('home/folder/my image.jpg');
?>

然后我将这段代码放在我的 public_html 文件夹中的一个 html 页面中:

<img src="/image.php">

当我加载页面时,它在我的浏览器中完美地显示了“my image.jpg”文件。所以这告诉我我确实可以访问我的 public_html 文件夹上方的文件夹(这是一个专用服务器),它告诉我我在渲染文件名中带有空格的 jpg 文件时没有问题。

所以现在我试图从同一个文件夹中提取随机图像,但似乎无法弄清楚。这是我正在做的但不起作用的事情。

我已经用这段代码创建了一个 image.php 文件并放在我的 public_html 文件夹中:

<?php

//Define Function to Select Random Image
function random_pic($dir = '/home/folder')
{
$files = glob($dir . '/*.jpg');
$file = array_rand($files);
return $files[$file];
}

//Select Random Image Path
$randPic = random_pic('/home/folder');

//Output Random Image When image.php is called from html image requests
header('Content-Type: image/jpeg');
readfile($randPic);
?>

然后我将这段代码放在我的 public_html 文件夹中的一个 html 页面中:

<img src="/image.php">

现在,当我使用这个 img 标签加载这个 html 页面时,我什么也得不到。没有错误,没有图像,只有空白。感谢任何人提供的任何见解。

【问题讨论】:

  • 调试步骤:检查glob() 是否真的在寻找反式(例如var_dump($files))。检查random_pic() 是否实际上返回了一个路径(例如var_dump($randPic)),然后检查 readfile 没有返回一个布尔值 false(你不能真正地 var_dump,因为浏览器会尝试将转储文本读取为图像数据)。
  • 做一个 file_exists($randPic);并 echo $randPic... 看看是否有意义。
  • 除了 Marc 所说的之外,我还考虑在标题中添加一个“no-cache”标志,这样他们就不会每次都得到相同的图像。或者,您可以使用302 Temporary Redirect 并直接指向图像文件,而不是使用readfile

标签: php image random root public-html


【解决方案1】:

为什么不使用绝对路径而不是

header('Content-Type: image/jpeg');
readfile('home/folder/my image.jpg');

像这样

// notice the absolute path prefix
if(!is_file($image_path = '/home/folder/my image.jpg')){
    header('Content-Type: text/plain', 404);
    echo 'Image file not found!';
}

// We got a file, keep going...
header('Content-Type: image/jpeg');
header('Content-Length: '.filesize($image_path));
readfile($image_path);

die; // done here

或者使用.php脚本当前目录的相对路径__DIR__.'/path/to/image.jpg'

【讨论】:

  • 我只是想确保我理解。所以关于拉随机图像,而不是使用这个代码: header('Content-Type: image/jpeg');读取文件($randPic);我应该用别的东西吗?看起来您从我的工作解决方案中引用了我的输出代码,而不是从我的非工作随机图像解决方案中引用。如果我误解了,我深表歉意。
  • @Bogarto 您的代码显然不错。您需要在random_pic 函数中输入var_dump($files),并确保您看到glob 结果列出的任何内容。这就是为什么我认为相对路径可能是一个问题......
【解决方案2】:

您必须关闭 safe_mode = off 或配置 open_basedir 才能访问图像目录。

【讨论】:

    猜你喜欢
    • 2012-05-02
    • 2014-03-07
    • 2021-07-07
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    相关资源
    最近更新 更多