Home >Backend Development >PHP Tutorial >How Can I Download Images from PHP URLs?

How Can I Download Images from PHP URLs?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-21 03:23:14831browse

How Can I Download Images from PHP URLs?

Downloading Images from PHP URLs

Downloading images from PHP URLs is a common task that can be achieved using a variety of methods. Let's consider a scenario where you wish to save an image from a URL like http://example.com/image.php, which contains a single image, to your PC with a new name.

Using allow_url_fopen

If the PHP configuration allows URL file opening:

$url = 'http://example.com/image.php';
$img = '/my/folder/flower.gif';
file_put_contents($img, file_get_contents($url));

Using cURL

If URL file opening is disabled, you can employ cURL:

$ch = curl_init('http://example.com/image.php');
$fp = fopen('/my/folder/flower.gif', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

These methods enable you to download and save images from PHP URLs with your desired file name, allowing you to incorporate images into your projects or save them for offline use.

The above is the detailed content of How Can I Download Images from PHP URLs?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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