2016-05-13 127 views
0

通过这篇文章 https://security.stackexchange.com/questions/32852/risks-of-a-php-image-upload-form我想去的地方showImage.php简单地由如何通过变量PHP图片

<?php 
header('Content-Type: image/jpeg'); 
readfile($pathToPicture); 
?> 

给,但我怎么能路过

<?php $pathToPicture = "server/www/images/imagexyz1823014719102714123.png"; ?> 

<img src="/resources/php/showImage.php" > 

,以显示我的图片的启发变量$ pathToPictureshowImage.php?我不想将$ pathToPictue改为showImage.php

+0

的可能的复制[如何通过使用GET而不型PHP变量?](http://stackoverflow.com/questions/6074699/how-to-pass-variables- in-php-using-get-without-type) – Chuck

回答

1

将image的路径作为get参数传递给showImage.php脚本。

<?php $pathToPicture = "server/www/images/imagexyz1823014719102714123.png"; ?> 

<img src="/resources/php/showImage.php?pathToPicture=<?php echo $pathToPicture;?>" > 

在这里你可以得到传递的变量从$_GET数组:

<?php 
    header('Content-Type: image/jpeg'); 
    readfile($_GET['pathToPicture']); 
?> 

我最好建议使用BASE64_ENCODE和BASE64_DECODE为pathToPicture用于这一目的。也不要公开像这样公开你的图像位置的整个路径。有一个看看下面改进的代码

<?php $pathToPicture = "imagexyz1823014719102714123.png"; ?> 

<img src="/resources/php/showImage.php?pathToPicture=<?php echo base64_encode($pathToPicture);?>" > 

<?php 
    $location = "server/www/images/"; 
    $image = !empty($_GET['pathToPicture']) ? base64_decode($_GET['pathToPicture']) : 'default.jpg'; 

    // In case the image requested doesn't exist. 
    if (!file_exists($location.$image)) { 
     $image = 'default.jpg'; 
    } 

    header('Content-Type: '.exif_imagetype($location.$image)); 
    readfile($location.$image); 
?> 
+1

请记住清理输入信息,否则您会遇到很多麻烦 –

+0

@TheCodingMonk是否足以致电htmlspecialchars或者您会推荐如何清理? – Adam

+0

检查传递的路径是否有效地指向图像文件夹,否则有人可能会读取服务器上的任意文件 –