Php save image from url


Php save image from url : There are many ways to save images from the the given url. file_get_contents and file_put_contents can be used to save images from the given url. For using the file_get_contents allow_url_fopen should be set true. Here in this tutorial we are going to explain how you can save an image from the url.


Php save image from url

Here are the methods you can use to save the image from given url –

Php save image from url : Using file_get_contents

If allow_url_fopen is set to true you can save image from given url as below –

Php save image from url : Using file_get_contents


$url = 'http://example.com/test-image.jpg';
$content = file_get_contents($url);
file_put_contents("/folder/myimage.jpg", $content);

Suppose that your image is on given url like – ‘http://example.com/test-image.jpg’ and you want to download it. First get the content of image using the function file_get_contents($url) where url is image full url. Now to save this image use the function file_put_contents(“/folder/myimage.jpg”, $content); where ‘/folder/myimage.jpg’ is folder name where you want to save the image with the name ‘myimage.jpg’ and $content contains the image content taken from the url.

Php save image from url : Using curl

You can save image from given url using the curl as below –

Php save image from url : Using Curl


$url = 'http://example.com/test-image.jpg';
$ch = curl_init($url);
$fp = fopen('/folder/myimage.jpg', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

The above example will save the image in folder with the name ‘myimage.jpg’.

Note : For using curl make sure the curl is enabled on your server.

Advertisements

Add Comment

📖 Read More