2016-11-03 113 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

相關問題