2012-02-05 39 views
2

我需要一個能夠從服務器上的文件夾下載多個圖像的php文件,並且每個圖像都有唯一的ID。如何通過一個獨特的PHP文件下載多個圖像?

例如

我有我的服務器上的圖像:/home/example/public_html/multipleimage/2.png

而且我想通過獨特的PHP文件來下載圖片:http://example.com/file.php

我會鍵入以下網址:http://example.com/file.php?id=2 而瀏覽器將不得不返回圖像。

但是...應該怎麼樣的PHP文件? 無需通過數據庫就可以完成嗎?

謝謝。

+0

你是什麼意思下載?你想讓用戶下載圖片嗎?或者服務器? – thelastshadow 2012-02-05 23:41:10

+0

服務器下載圖像 – ignaces 2012-02-05 23:44:17

回答

4
<?php 
header("Content-Type: image/png"); 
readfile(
    sprintf(
     '/home/example/public_html/multipleimage/%d.png', 
     $_GET['id'] 
    ) 
); 

查看PHP手冊中的以下條目:

注意,我一個m使用sprintf%d,所以它會默默地將任何非數字ID值轉換爲0,所以像../../etc/passwd這樣的惡意輸入將嘗試讀取0.png。如果你想用別的什麼,只是數字,你需要淨化輸入,以防止directory traversal attacksnull byte poisoning (before PHP 5.3.4)

+0

非常感謝!它工作完美。 – ignaces 2012-02-06 00:03:43

0

我仍然不知道我知道你想要什麼,但這裏有雲:

<?php 
if (array_key_exists('id', $_GET) && is_numeric($_GET['id'])) { 
    header("Content-Type: image/png"); 
    echo file_get_contents("/home/example/public_html/multipleimage/".$_GET['id'].".png"); 
} 

?>