【问题标题】:Displaying images from outside of web root not working?显示来自 Web 根目录之外的图像不起作用?
【发布时间】:2017-03-16 15:13:04
【问题描述】:

我正在尝试显示存储在 Web 根目录之外的用户图像(出于安全目的)。我已经尝试过提出here 的建议,但是当我导航到show_imgs.php 时,我的浏览器返回一堆乱码,似乎进入了无限循环。

我的代码与示例的唯一不同之处在于我的代码处于循环状态。不确定这是否与它有关。

我的代码:

$image_array = ["img_1.png", "img_2.png", "img_3.png"];

$i = 1;
foreach($image_array as $image) {

    //Specify absolute path
    $image_path = "/absolute/path/to/img_$i.png";

    //Get file contents. I have also tried readfile() in place of this.
    $contents = file_get_contents($image_path);

    //Perhaps this is causing the infinite loop?
    header('Content-type: image/png');

    //Display contents of file (aka the image)
    echo $contents;

    $i++;
}

当然,在使用file_get_contents 进行安全检查之前,我会想添加文件大小和mime 类型验证(如果我应该做更多安全检查,请说出来)。

【问题讨论】:

    标签: php html security


    【解决方案1】:

    您将无法循环发送多张图片。一个 php 文件将输出一个标题和一个图像。您必须再次调用它才能获取另一张图片。

    “这样你就可以调用像这样的图像:”

    /image.php?file=myfile.jpg

    其中 images.php 是其中读取了标题和图像的 php 文件。

    images.php:

    $file = basename(urldecode($_GET['file']));
    $fileDir = '/path/to/files/';
    
    if (file_exists($fileDir . $file)) {
        // Note: You should probably do some more checks 
        // on the filetype, size, etc.
        $contents = file_get_contents($fileDir . $file);
    
        // Note: You should probably implement some kind 
        // of check on filetype
        header('Content-type: image/jpeg');
    
        echo $contents;
    }
    

    my.html:

    <img src="images.php?file=myimage.jpg" alt="">
    

    【讨论】:

    • 所以你是说我应该在images.php中做这些操作,然后在display_the_images.php中调用图片?这是否必须在 URL 中完成,然后使用 GET 或仅在 display_the_images.php 的 PHP 脚本中完成?
    • 所以一个文件(示例中为 images.php ......但你可以随意命名它)中包含 php,它将“去获取并读出”文档根目录之外的图像。然后在您通常放置图像的 html 中...您将带有 GET var 的 php 文件放在其上,以让 images.php 知道要获取哪个图像。
    猜你喜欢
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 2017-10-09
    相关资源
    最近更新 更多