简体   繁体   中英

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 = @imagecreatefromstring($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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM