Saving the Remote Image File from a URL in PHP
PHPIn 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];
if (in_array($imgType, array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP))) {
$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:
- Index 0: width of the image
- Index 1: height of the image
- Index 2: type of the image
- Index 3: text string of width and height
- mime: MIME type of the image
- channels: 3 for RGB pictures and 4 for CMYK pictures
- 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.