How Can I Save an Image from a URL Using cURL in PHP?
Nov 25, 2024 am 12:49 AMSave 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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel

Build a React App With a Laravel Back End: Part 2, React

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon

Announcement of 2025 PHP Situation Survey
