Search code examples
phpimageuploadreadfileoutput-buffering

Saving a remote image programmatically with PHP


I am trying to migrate some content from one resources into another and need to save some images (several hundred) located at a remote resource.

Suppose I have only the URL to an image:

https://www.example.com/some_image.jpg

And I would like to save it into the filesystem using PHP.

If I were uploading the image, I essentially would do the following:

<input type="file" name="my_image" />

move_uploaded_file($_FILES['my_image']['tmp_name'], '/my_img_directory');

But since I only have the URL, I would imagine something like:

$img = 'https://www.example.com/some_image.jpg';
$file = readfile($img);
move_uploaded_file($file, '/my_img_directory');

Which of course wouldnt work since move_uploaded_file() doesn't take an output buffer as a first argument.

Essentially, I would need to get $img into the $_FILES[] array under this approach. Or may some other approach?


Solution

  • You can use PHP's copy function to copy remote files to a location on your server:

    copy("https://example.com/some_image.jpg", "/path/to/file.jpg");
    

    http://php.net/manual/en/function.copy.php