PHP - Copy image to my server direct from URL

To copy an image from a URL and save it to your server using PHP, you can use the following function:

<?php

function save_image($inPath, $outPath)
{
  $in = fopen($inPath, "rb");
  $out = fopen($outPath, "wb");
  while ($chunk = fread($in, 8192)) {
    fwrite($out, $chunk, 8192);
  }
  fclose($in);
  fclose($out);
}

Watch a course Learn object oriented PHP

You can then call the function and pass in the URL of the image as the $inPath parameter and the desired location and name for the saved image on your server as the $outPath parameter.

For example:

<?php

$inPath = 'http://www.example.com/images/image.jpg';
$outPath = '/path/to/save/location/image.jpg';
save_image($inPath, $outPath);

This will download the image located at http://www.example.com/images/image.jpg and save it to /path/to/save/location/image.jpg on your server.