2016-11-03 68 views
0

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

唯一不同的关于我的代码与例子是我的代码是在一个循环中。不知道这与它有什么关系。

我的代码:

$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类型的验证(如果有更多的安全检查,我应该做的请告诉我)。

回答

0

您将无法循环并发送多个图像。一个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=""> 
+0

所以你说我应该在images.php做这些操作,然后调用display_the_images图像.PHP?这是否必须在URL中完成,然后使用GET,还是只能在display_the_images.php的PHP脚本中完成? – faceymcface

+0

所以只有一个文件(例子中的images.php,但你可以任意命名)有php,它将“读取和读出”doc根目录以外的图像。然后在你通常放置图像的html文件中...你把这个带有GET var的php文件放在它上面让image.php知道要去哪个图像。 – WEBjuju

+0

这工作!谢谢你,先生 – faceymcface

相关问题