【问题标题】:PHP / HTML - Load image from outside root folderPHP / HTML - 从外部根文件夹加载图像
【发布时间】:2016-09-03 18:47:53
【问题描述】:

我正在尝试在 HTML 中的 <img> 标记中加载图像。 我的 images 文件夹与根文件夹在同一个文件夹中,这意味着我需要上一个文件夹才能访问 images 文件夹。

我浏览了互联网,找到了在图像的 src 属性中使用 GET 请求的方法,不幸的是没有成功。

文件夹结构:

img >
    somefile.png
    foo.png
    bar.png
html >
    index.php
    imageRequest.php
    //other root files

我不能使用以下内容:<img src="../img/somefile.png">,因为它指向不存在的东西(呃!)。所以我尝试使用 GET 请求。

我的 HTML

<div>
   <img src="imageRequest.php?requested=somefile.png">
</div>

我的 PHP (imageRequest.php)

    $fileName = $_GET['requested'];
    fetchImage();

    function fetchImage(){
        global $fileName;
        if(!isset($fileName)) return;
        $filePath = dirname($_SERVER['DOCUMENT_ROOT'])."/img/".$fileName;
        if(file_exists($filePath)){
            readfile($filePath);
        }
    }

TL;DR:使用&lt;img&gt; 标记内根文件夹之外的文件夹中的图像。

【问题讨论】:

  • 因为你的文件夹在你的根目录之外,你不能使用DOCUMENT_ROOT...如果你有权限你可以在你的函数fetchImage()中使用绝对路径。我还建议您将变量 $fileName 传递给您的函数并且不要在那里使用全局变量。
  • @RaphaelMüller 目录名($dir);抓取父文件夹,这是我需要的文件夹;)。不过感谢您的提示。

标签: php html image


【解决方案1】:

使用 PHP 作为 base64 图像获取该图像并输出该内容以及适当的标题:

[imageRequest.php?requested=some_file.png]

$imagesDir = __DIR__.'/../';
$content = file_get_contents($imagesDir.$_GET['requested']);
$content = base64_encode($content);

$data = "data:image/png;base64,{$content}";

header('Content-Type: image/png');
echo base64_decode($data);`

【讨论】:

  • 请注意,您可以轻松注入另一条路径。你必须检查它是否真的是一个图像。否则有可能访问配置文件等等......
  • @RaphaelMüller 是的,我的代码不包含任何安全检查。 OP 必须检查有效的图像名称、有效的get 参数、验证图像是否存在等等
  • 有一个重写规则也很好,这样在 html 源代码中它更容易使用。例如/someimagesource/some_file.png 被重写为 imageRequest.php?requested=some_file.png
  • @RaphaelMüller 这与 OP 问题无关。但作为旁注,您可以映射任何扩展名为 png|jpg|jpeg|png 的文件都会导致此功能,而 url 可能看起来像 example.com/some_file.png
  • @Justinas '[' 之间的部分应该在 src="" 对吗?目前它似乎不起作用。它显示“无图像”图标。
猜你喜欢
  • 2015-08-21
  • 1970-01-01
  • 1970-01-01
  • 2019-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-04
相关资源
最近更新 更多