Home > Backend Development > PHP Tutorial > How Can I Save JPEG Images from PHP URLs with and without `allow_url_fopen`?

How Can I Save JPEG Images from PHP URLs with and without `allow_url_fopen`?

DDD
Release: 2024-12-19 19:08:11
Original
906 people have browsed it

How Can I Save JPEG Images from PHP URLs with and without `allow_url_fopen`?

Saving JPEG Images from PHP URLs

When encountering the need to retrieve and store images from external URLs within a PHP environment, various techniques come into play. One common challenge arises when trying to preserve JPEG image files from a specified PHP URL.

To effectively capture these images and store them on your local PC, several approaches can be employed. One method involves utilizing the allow_url_fopen configuration. If this setting is enabled, you can directly retrieve the image contents and save them locally:

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

In this example, the image is fetched from the specified URL (in this case, http://example.com/image.php) and stored as flower.gif within the my/folder directory on your local computer.

However, if allow_url_fopen is disabled for security reasons, an alternative technique involving cURL may be implemented:

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

Utilizing cURL, the image is once again obtained from the URL and saved as flower.gif in the specified local directory. This method provides a robust and reliable solution when working with external image URLs.

The above is the detailed content of How Can I Save JPEG Images from PHP URLs with and without `allow_url_fopen`?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template