You have an image in a URL, something like “https://www.lab-informatika.com/images/sample.png“, and you want to save that image in your computer, but you want to obtain that directly from PHP. How to do that? Saving images from any live url is very easy with php. Here are three ways to do this.
- Using Curl
- Using File functions
- Using GD library functions.
Using Curl
To use this method, CURL extension needs to be installed in your php environment. So here is the function for grabbing and saving an image using Curl.
function save_image($url, $output)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$raw = curl_exec($ch);
curl_close($ch);
if (file_exists($output)) {
unlink($output);
}
$fp = fopen($output, 'x');
fwrite($fp, $raw);
fclose($fp);
}
Using File functions
function save_image($url, $output)
{
$in = fopen($url, "rb");
$out = fopen($output, "wb");
while ($chunk = fread($in,8192))
{
fwrite($out, $chunk, 8192);
}
fclose($in);
fclose($out);
}
Using GD library functions.
To use this method, you have to set allow_url_fopen to on. The allow_url_fopen directive is disabled by default.
function save_image($url, $output)
{
$img = imagecreatefromjpeg($url);
imagejpeg($img, $output);
}
How to use
Now, we can save any images from live URL using below command.
save_image("https://www.lab-informatika.com/images/sample.jpg", "path/sample.jpg")
No Comments
Leave a comment Cancel