2012-03-16 44 views
1

我需要向我的頁面pic.php發送一個GET請求,並且我想獲得一張真實圖片作爲回報。PHP - 發送GET請求並獲取圖片作爲回報

現在我實現了這個想法是這樣的:

<?php 
if ((isset($_GET['pic']))&&(isset($_GET['key']))){ 
$pic = $_GET['pic']; 
$pic=stripslashes($pic); 

header('Location: /content/'.$pic); 

} 
?> 

但它不是我真正想要的東西 - 它直接重定向到的圖像。我想要的是保持相同的URL,但取決於提交的值取決於需要的文件。 這樣做的最好方法是什麼? thx。

+2

http://stackoverflow.com/questions/7069112/can-i-echo-a-jpg-image-through-php-without-processing-it – miki 2012-03-16 17:49:50

+0

嘗試'的file_get_contents( '/內容/'。 $ pic);' – Ascherer 2012-03-16 17:54:26

+0

對此我不是100%,但我認爲文件上傳必須是POST請求。簡單的參考。 http://www.w3schools.com/php/php_file_upload.asp – laymanje 2012-03-19 18:35:44

回答

3

此示例代碼片段應該按照您的要求進行操作。如果在服務器上啓用了魔術引號,我還包含了代碼去除斜槓。這將使您的代碼更加便攜,並且與未來版本的PHP兼容。我還添加了使用getimagesize()來檢測MIME類型,以便爲圖像輸出正確的標題,而不必假定它是特定類型的。

<?php 
if(isset($_GET['pic'])) 
{ 
    //Only strip slashes if magic quotes is enabled. 
    $pic = (get_magic_quotes_gpc()) ? stripslashes($_GET['pic']) : $_GET['pic']; 

    //Change this to the correct path for your file on the server. 
    $pic = '/your/path/to/real/image/location/'.$pic; 

    //This will get info about the image, including the mime type. 
    //The function is called getimagesize(), which is misleading 
    //because it does much more than that. 
    $size = getimagesize($pic); 

    //Now that you know the mime type, include it in the header. 
    header('Content-type: '.$size['mime']); 

    //Read the image and send it directly to the output. 
    readfile($pic); 
} 
?> 
2

我可以看到你在兩個方面這樣做:

1)返回的URL圖像,並打印出的圖像標籤:

print '<img src=' . $img_url . ' />'; 

2)或者,你可以只拉數據的圖像,並顯示它。例如,適當設置標題,然後僅打印圖像數據。

header("content-type: image/png"); 
print $img_data; 

這裏假定你有圖像數據存儲在字符串$ img_data中。此方法也會阻止您在頁面上顯示其他內容。您只能顯示圖像。

0

您可以加載圖像,發送圖像頭,並顯示圖像這樣:

header('Content-Type: image/jpeg'); 
readfile('/path/to/content/pic.jpg'); 

顯然頭將取決於文件類型,但是這容易使動態。

0

不知道如果我明白你在做什麼之後,但猜測你想要在img標籤中加載圖片?

如果我是正確的,你只是做:

<img src=http://www.domain.com/pic.php?"<?php echo image here ?>" /> 

基本上你只要把圖片的來源,你得到引導到該圖像是網頁。