Tuesday, 03 September 2019

Saving the Remote Image File from a URL in PHP


In PHP, it is easy to check an image file properties and save the image file from a remote web server.

$fileUrl = 'http://www.theremoteserver.com/image-file.jpg';
$fileInfo = getimagesize($fileUrl);
$imgType = $fileInfo[2];

    $width = $fileInfo[0];
    $height = $fileInfo[1];
    $imgTag = $fileInfo[3];
    echo 'Width: '.$width.'<br>';
    echo 'Height: '.$height.'<br>';
    echo 'Image Tag: '.$imgTag.'<br>';
    echo 'MIME: '.$fileInfo['mime'].'<br>';
    $file   = file($fileUrl);
    $imgFileName = basename($fileUrl);
    $result = file_put_contents($imgFileName, $file);
    echo 'File has been saved!';

In the above code snippet, function getimagesize() is used to get the image file properties. It returns an array with up to 7 elements:

  1. Index 0: width of the image
  2. Index 1: height of the image
  3. Index 2: type of the image
  4. Index 3: text string of width and height
  5. mime: MIME type of the image
  6. channels: 3 for RGB pictures and 4 for CMYK pictures
  7. bits: number of bits for each color

In line 5, the returned image type (index 2) is used to check whether the remote image file is GIF, JPEG, PNG or BMP. Details of the image types are predefined in image constants. Then the image file properties, width, height, text string of width and height and MIME type are printed out. The function file() reads the entire file into an array from the remote web server. And the function file_put_contents() is used to write the data into a file.