Home > Backend Development > PHP Tutorial > How Can I Save Images from URLs to My Server Using cURL in PHP?

How Can I Save Images from URLs to My Server Using cURL in PHP?

Linda Hamilton
Release: 2024-11-23 07:03:23
Original
783 people have browsed it

How Can I Save Images from URLs to My Server Using cURL in PHP?

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);
Copy after login

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template