Automatically Upload Images with PHP Directly from the URI

It is a simple task to upload images on the server with PHP using a simple web form. Than everything’s in the $_FILES array and after submitting the form the file’s on the server. By simply move_uploaded_file you can change its location on the server to the desired folder.

However is there a way to “upload” files without using a web form, but only by telling the PHP script where to find the image. First and most important the image should be web visible and accessible by HTTP.

The solution is quite easy – you can grab the file using file_get_contents, and than put it on the desired server folder with file_put_contents. Here’s some source:

$image = file_get_contents('http://www.example.com/image.jpg');
file_put_contents('/var/www/my.jpg', $image);

Extending the Case

You can go even further by downloading any kind of files with the same approach. What will be the case for an mp4 video is shown in the next example:

$video = file_get_contents('http://www.example.com/video.mp4');
file_put_contents('/var/www/my.mp4', $video);

Usage

This can be quite useful when trying to automate an remote upload process. In this case when somebody uploads an image on his site, you can duplicate this file on your server! However don’t forget the copyrights!

4 thoughts on “Automatically Upload Images with PHP Directly from the URI

  1. I really don’t see any use for this. Why would you always need to edit your php file (open ftp, open file for editing) when you could just save and upload the photo from your website. It’s much faster by downloading and uploading then to edit php files on your server to download a photo you want

  2. Great tip. Thanks. @Bakecaincontriudine….. WOW. one use is you write an upload.php file using $_GET to link a javascript to your upload.php.

Leave a Reply

Your email address will not be published. Required fields are marked *