W3docs

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:

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

Example of copying image to the server directly from URL in PHP

<?php

function save_image($inPath, $outPath)
{
  $context = stream_context_create(['http' => ['timeout' => 30]]);
  $in = fopen($inPath, "rb", false, $context);
  if ($in === false) {
    return false;
  }
  $out = fopen($outPath, "wb");
  if ($out === false) {
    fclose($in);
    return false;
  }
  while (!feof($in) && ($chunk = fread($in, 8192))) {
    fwrite($out, $chunk);
  }
  fclose($in);
  fclose($out);
  return true;
}

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

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:

Example of copying an image from a URL and saving it to the server using PHP

<?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.

Alternatively, PHP provides a built-in copy() function that simplifies this exact task: copy($inPath, $outPath);