2016-05-13 69 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

檢查傳遞的路徑是否有效地指向圖像文件夾,否則有人可能會讀取服務器上的任意文件 –