Mask
Mask

Reputation: 34217

How to download an image with PHP?

Suppose the url of the image is here:

http://sstatic.net/so/img/logo.png

How to download it with PHP?

Upvotes: 0

Views: 1081

Answers (3)

nsilberman
nsilberman

Reputation: 1

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);

Upvotes: 0

RageZ
RageZ

Reputation: 27323

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.

Upvotes: 3

mtvee
mtvee

Reputation: 1565

$fp = fopen('logo.png', 'w');
fwrite($fp, file_get_contents('http://sstatic.net/so/img/logo.png'));
fclose($fp);

Upvotes: 4

Related Questions