I am trying to obtain and display a remote image from a url in PHP. Most images work, however开发者_运维技巧 some images redirect for example:
http://thundafunda.com/33/World-tour/download/Grand%20Canal,%20Venice,%20Italy%20pictures.jpg
The image would load and then disappear. I am using an IMG tag and placing that url as the source. Any idea?
Using this portion of code, that doesn't do anything except display an <img>
tag :
$url = 'http://thundafunda.com/33/World-tour/download/Grand%20Canal,%20Venice,%20Italy%20pictures.jpg';
echo '<img src="' . $url . '" alt="" />';
I get the same kind of behavior you are describing : the image is not displayed.
If I take a look at what's happening on the network level, using Firebug, I see this :
(source: pascal-martin.fr)
Basically :
- A request is made to load the image
- The image loads
- But the response comes with :
- a
302
HTTP status code - That redirects to the URL given in the
Location
header of the response -- which points to an HTML page
- a
- So, the browser follows that redirection
- and loads an HTML page
Which, of course, cannot be displayed in an <img>
tag.
If you do exactly the same test, disabling the Referer
(some Firefox extensions can do that), you'll see the image is displayed properly -- and Firebug says :
(source: pascal-martin.fr)
Note that there is no Referer header, this time, in the Request sent from my Browser.
Considering this, I would bet there is some kind of anti-hot-linking protection that's been setup by the website hosting that image...
And there is not much you can do, except host the file on your own server -- if the licence allows you to.
The server prevents hot linking of images, probably based on the referrer. There are ways around this, e.g the use of curl (if installed on your server):
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://thundafunda.com/33/World-tour/download/Grand%20Canal,%20Venice,%20Italy%20pictures.jpg');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, 'http://thundafunda.com/');
$imageData = curl_exec($ch);
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: image/jpg");
header("Content-Transfer-Encoding: binary");
echo $imageData;
Disclaimer:
They probably don't like hot linking of images, otherwise they wouldn't have integrated their solution in the first place. Better ask them for permissions to use their images, otherwise it might infringe their copyright
精彩评论