How to Download and Save an Image from a URL to Server with PHP using Copy or file_get_contents?

Patricia Arquette
Release: 2024-10-18 22:55:30
Original
172 people have browsed it

How to Download and Save an Image from a URL to Server with PHP using Copy or file_get_contents?

Copying Images from URLs to Server using PHP

Question:

How can I create PHP code to download an image from a specified URL and save it directly on my server with 777 permissions?

Answer:

Option 1 (PHP5 or higher):

Use the copy() function:

<code class="php">copy('http://www.google.co.in/intl/en_com/images/srpr/logo1w.png', '/tmp/file.png');</code>
Copy after login

Option 2 (PHP4 and below):

Use file_get_contents() to retrieve the image and fopen() and fwrite() to save it:

<code class="php">// Get the image
$content = file_get_contents("http://www.google.co.in/intl/en_com/images/srpr/logo1w.png");

// Save the image
$fp = fopen("/location/to/save/image.png", "w");
fwrite($fp, $content);
fclose($fp);</code>
Copy after login

Note: To set 777 permissions on the downloaded image, use the chmod() function after download:

<code class="php">chmod("/tmp/file.png", 0777); // or chmod("/location/to/save/image.png", 0777)</code>
Copy after login

The above is the detailed content of How to Download and Save an Image from a URL to Server with PHP using Copy or file_get_contents?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!