Home >Backend Development >PHP Tutorial >How Can I Download Images from a URL using PHP and Curl?
Downloading Image Files via URL Using PHP and Curl
Saving image files from a remote URL to your server is a common task for web developers. This can be achieved seamlessly using PHP's Curl extension.
The Problem:
A developer has encountered difficulties saving an image file from a URL using Curl. The code provided does not seem to produce the desired result.
The Solution:
Here's a modified version of the code that should resolve the issue:
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); }
Key Changes:
Additional Tip:
In your PHP configuration file (php.ini), ensure that allow_url_fopen is enabled. This setting allows PHP to open files via URLs.
The above is the detailed content of How Can I Download Images from a URL using PHP and Curl?. For more information, please follow other related articles on the PHP Chinese website!