Get file type for images that do not have an extension in PHP and WordPress

I am creating a website/theme using WordPress. I am retrieving a number of images from various websites. Some images do not come with extensions, but they are rendered correctly in the browser.

All of that is fine, but I also need to get the file type, and I am using this:

Read More
$filetype = wp_check_filetype(basename($image_file_name), null );

Now, if the file name of the image retrieved does have an extension, say jpg, then the output of the above call is

Array
(
    [ext] => jpg
    [type] => image/jpeg
)

However if the extension is not part of the file name then the call above returns the following array

Array
(
    [ext] =>
    [type] =>
)

Obviously something is not right, I may have to change how to check for the file type rather than rely on the extension, but I do not have an idea how to do this. How do I check that? How do I retrieve the file type from an image that does not have an extension?

Thanks.

Related posts

Leave a Reply

1 comment

  1. Try to use finfo_file. I’ve used it to check the type of a file uploaded through a form.
    Here’s the code that I’ve used in my application

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, 'name_of_your_file_with_or_without_extension');
    

    Hope this will help :).