2012-03-16 79 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 ?>" /> 

基本上你只要把图片的来源,你得到引导到该图像是网页。