Saving Files from URLs with CURL in PHP
In a bid to store an image from a specified URL onto a directory on a server, understanding how to utilize CURL in PHP is vital. Below are possible steps to achieve this:
Original Code:
function GetImageFromUrl($link) { $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 0); curl_setopt($ch,CURLOPT_URL,$link); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($ch); curl_close($ch); return $result; } $sourcecode = GetImageFromUrl($iticon); $savefile = fopen(' /img/uploads/' . $iconfilename, 'w'); fwrite($savefile, $sourcecode); fclose($savefile);
Improved Solution:
To enhance the functionality of the provided code, an alternative method is recommended:
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); }
Additional Recommendation:
In your php.ini file, ensure that allow_url_fopen is set to enabled. This setting is crucial for enabling external URL access.
The above is the detailed content of How Can I Save Images from URLs to My Server Using cURL in PHP?. For more information, please follow other related articles on the PHP Chinese website!