What are the best practices for efficiently retrieving the file type of an image from an external URL in PHP without loading unnecessary data?
When retrieving the file type of an image from an external URL in PHP, it's important to do so efficiently without loading unnecessary data. One way to achieve this is by sending a HEAD request to the URL and checking the Content-Type header of the response. This allows us to retrieve the file type without downloading the entire image.
<?php
function getImageTypeFromURL($url) {
$headers = get_headers($url, 1);
if (isset($headers['Content-Type'])) {
return $headers['Content-Type'];
}
return false;
}
$imageURL = 'https://example.com/image.jpg';
$imageType = getImageTypeFromURL($imageURL);
if ($imageType) {
echo "Image type: $imageType";
} else {
echo "Unable to retrieve image type.";
}