Using WordPress ‘wp_check_filetype()’ PHP function

The wp_check_filetype() WordPress PHP function fetches the file type from a file name. It can be helpful when you need to determine the extension or MIME type of a particular file.

Usage

Here’s a general usage of the function with a custom example showing its input and output:

$filetype = wp_check_filetype('document.pdf');
echo $filetype['ext'];  // will output "pdf"

Parameters

  • $filename (string) [Required]: This is the file name or path.
  • $mimes (string[]) [Optional]: This is an array of allowed MIME types, keyed by their file extension regex. The default value is null, which defaults to the result of get_allowed_mime_types().

More information

See WordPress Developer Resources: wp_check_filetype() Please note that the wp_check_filetype() function was implemented in WordPress version 2.5.0.

Examples

Checking a JPEG Image

In this example, we are checking the filetype of a JPEG image.

$filetype = wp_check_filetype('image.jpeg');
echo $filetype['ext']; // will output "jpeg"

Checking a GIF Image

Here, we want to find out the filetype of a GIF image.

$filetype = wp_check_filetype('animation.gif');
echo $filetype['ext']; // will output "gif"

Checking a Word Document

We can also check the filetype of a Word document with this function.

$filetype = wp_check_filetype('report.docx');
echo $filetype['ext']; // will output "docx"

Checking an MP3 Audio File

If we need to determine the filetype of an MP3 audio file, we can do so as follows.

$filetype = wp_check_filetype('song.mp3');
echo $filetype['ext']; // will output "mp3"

Checking a Video File

Finally, we can check the filetype of a video file like this.

$filetype = wp_check_filetype('movie.mp4');
echo $filetype['ext']; // will output "mp4"

Remember, in all these examples, if the file does not match a MIME type, the output will be false.