How to download an image with PHP?
Sup开发者_Python百科pose the url of the image is here:
http://sstatic.net/so/img/logo.png
How to download it with PHP?
$fp = fopen('logo.png', 'w');
fwrite($fp, file_get_contents('http://sstatic.net/so/img/logo.png'));
fclose($fp);
I would a plain file_get_contents
and file_put_contents
would do it
$content = file_get_contents('http://sstatic.net/so/img/logo.png')
file_put_contents('logo.png', $content);
have to be noted that with that way of doing the whole file will be stocked in memory, so you have to be careful about the memory_limit
. If you need a method without puting the file in memory curl would do it.
You can use a curl request :
public static function curlGet($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
and write the content response into a file
$fp = fopen('logo.png', 'w');
fwrite($fp, curlGet('http://sstatic.net/so/img/logo.png') );
fclose($fp);
精彩评论