Home > Article > Backend Development > How to Copy Images from URL to Server Using PHP?
When working with web applications, it often becomes necessary to download images from external URLs to store them locally on the server. PHP offers multiple ways to achieve this task.
For PHP versions 5 and above, the 'copy()' function provides a straightforward method to copy files from remote URLs to the server. The syntax is as follows:
<code class="php">copy('http://example.com/image.png', '/path/to/local/image.png');</code>
If PHP5 is not available, the file_get_contents() and fopen() functions can be used together. The first function retrieves the image content from the URL, and the second function saves the content to a file on the server:
<code class="php">$content = file_get_contents('http://example.com/image.png'); $fp = fopen('/path/to/local/image.png', 'w'); fwrite($fp, $content); fclose($fp);</code>
To ensure that the image is stored with the appropriate permissions, set the proper file permissions (e.g., 777) after copying the file.
The above is the detailed content of How to Copy Images from URL to Server Using PHP?. For more information, please follow other related articles on the PHP Chinese website!