How can get an image from a 301 redirect download link in PHP?
I'm trying to download this image with PHP to edit it with GD. I found many solutions for image links, but this one is a download link.
Edit:
$curl = curl_init("http://minecraft.net/skin/Notch.png");
$bin = curl_exec($curl);
curl_close($curl);
$img = @imagecreatefrom开发者_StackOverflow社区string($bin);
This is my current code. It displays "301 Moved Permanently". Are there CURLOPTs I have to set?
$curl = curl_init("http://minecraft.net/skin/Notch.png");
// Moved? Fear not, we'll chase it!
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
// Because you want the result as a string
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$bin = curl_exec($curl);
curl_close($curl);
$img = @imagecreatefromstring($bin);
Here is an option to directly save the image to a file (instead of using imagecreatefromstring
):
<?php
$fileName = '/some/local/path/image.jpg';
$fileUrl = 'http://remote.server/download/link';
$ch = curl_init($fileUrl); // set the url to open and download
$fp = fopen($fileName, 'wb'); // open the local file pointer to save downloaded image
curl_setopt($ch, CURLOPT_FILE, $fp); // tell curl to save to the file pointer
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // tell curl to follow 30x redirects
curl_exec($ch); // fetch the image and save it with curl
curl_close($ch); // close curl
fclose($fp); // close the local file pointer
fopen
- depends on your php settings if url fopen is allowed.
or curl
see the fine php manual.
精彩评论