Greeso
Greeso

Reputation: 8219

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:

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

Upvotes: 1

Views: 296

Answers (1)

fusillicode
fusillicode

Reputation: 83

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 :).

Upvotes: 2

Related Questions