How Can I Save an Image from a URL Using cURL in PHP?

Susan Sarandon
Release: 2024-11-25 00:49:09
Original
184 people have browsed it

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

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

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!

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