Home >Backend Development >PHP Tutorial >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>
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>
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>
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!