【问题标题】:Display image from outside the web root ( public_html )从 Web 根目录 (public_html) 外部显示图像
【发布时间】:2017-09-03 20:48:51
【问题描述】:

背景:

  • 我有一个文件夹,其中包含名为 uploads 的图像或位于网站根目录之外的图像。 (在 public_html 之外)
  • 我正在尝试打印里面的图像,比如说 image.php。

执行规则:

  • 我正在尝试在 .htaccess 中不使用别名 mod_rewrite 来实现。
  • 中间不显示黑色背景和图像(我不希望像浏览domain.com/image.png时那样。就像我下面提到的图片示例。
  • 不使用其他页面并将其作为 get 传递。

我尝试了什么:

  • 我查了很多问题,其中一个是this,另一个是 this.
  • 根据上面提出的当前问题和其他教程,我想出了 这个:

    <?php
    
    $location = dirname($_SERVER['DOCUMENT_ROOT']);
    $image    = $location . '/public_html/images/banned.png';
    
    header('Content-Type:image/png');
    header('Content-Length: ' . filesize($image));
    echo file_get_contents($image);
    
    ?>
    
    <img src=" <? echo $image; ?> "/>
    

效果很好,下面是一个例子:

Gyazo


但是,这不是我正在寻找或尝试做的事情。同样,我试图将其视为普通图像 src,因为它将用于个人资料图片或其他用途。

任何帮助将不胜感激。提前致谢!

【问题讨论】:

  • 我认为问题在于您发送的内容类型,您是否尝试将其删除?
  • 我尝试删除它,但它显示像“�PNG IHDR”这样的十六进制代码,当我尝试 bin2hex 时,页面显示一个空白页。
  • �PNG 是 PNG 文件,而您使用的是 Content-Type:image/jpeg
  • @Fred-ii- 是的,我从我的文件中将其更改为 image/png,但我忘了从这里更改,抱歉。
  • 好吧,现在问题不清楚了,$file 也是如此,它的价值是什么?除非你的意思是$image

标签: php html image


【解决方案1】:

把你的 image.php 改成

<?php
function image() {
$location = dirname($_SERVER['DOCUMENT_ROOT']);
$image    = $location . '/public_html/images/banned.png';

return base64_encode(file_get_contents($image));
}
?>

在另一个要显示该图像的文件中,比如说 test.php:

<?php
include("image.php");
?>
<img src='data:image/png;base64,<?= image(); ?>' >

【讨论】:

    【解决方案2】:

    这个:

    echo file_get_contents($image);
    ?>
    
    <img src=" <? echo $image; ?> "/>
    

    有几个原因是错误的。首先,您不能以这种方式将原始图像内容与 HTML 标记混合。 src 还指定图像的 URL,而不是原始内容。

    您可以将 echo file_get_contents($image); 和相关代码移动到单独的文件,即 image.php,然后在 src 中引用它,将图像名称作为参数传递(即 image.php?img=foo.jpg) - 请注意,如果您这样做这个错了,你会打开directory traversal attack)。或者,您可以尝试使用 rectory traversal attackdata URI scheme 作为 src 参数并以这种方式直接传递原始内容。

    【讨论】:

      猜你喜欢
      • 2018-02-04
      • 1970-01-01
      • 1970-01-01
      • 2017-03-16
      • 1970-01-01
      • 2017-10-09
      • 2012-09-18
      • 2012-01-30
      • 1970-01-01
      相关资源
      最近更新 更多