Home > Article > Backend Development > How Can I Save an Image from a URL Using cURL in PHP?
Save an Image File from a URL Using CURL in PHP
Problem:
You're attempting to download and save an image file from a remote URL using CURL, but your current code isn't working as expected.
Solution:
Instead of the code provided, try the following function:
function grab_image($url, $saveto) { $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($saveto)) { unlink($saveto); } $fp = fopen($saveto, 'x'); fwrite($fp, $raw); fclose($fp); }
To use this function, call it with the URL of the image file and the path to the file where you want to save it on your server. Ensure that PHP's allow_url_fopen parameter is enabled in php.ini.
Example:
grab_image('https://example.com/image.png', '/path/to/save/photo1.png');
This function allows you to grab an image from a remote URL and save it as a file on your server.
The above is the detailed content of How Can I Save an Image from a URL Using cURL in PHP?. For more information, please follow other related articles on the PHP Chinese website!