wp_check_filetype()WP 2.0.4

Gets the file extension and MIME type by the given filename (path). Used to check whether the specified file type is allowed to be uploaded to the site.

In the second parameter you can specify allowed file types. By default they are obtained by the function get_allowed_mime_types().

1 time — 0.0011148 sec (very slow) | 50000 times — 1.85 sec (fast) | PHP 7.3.12, WP 5.4.1

No Hooks.

Returns

Array. File type data:

array(
	'ext' => 'png',        // extension (e.g. 'jpg')
	'type' => 'image/png', // mime type (e.g. 'image/jpeg')
)

If the file type is not allowed, each element of the array will contain false.

Usage

wp_check_filetype( $filename, $mimes )
$filename(string) (required)
Absolute path to the file: www/example.com/wp-content/uploads/file.png
$mimes(array)
Array of names of allowed extensions and file types. By default the values come from the function get_allowed_mime_types().
Default: null

Examples

1

#1 Demo

$file = dirname(__FILE__) . '/image.jpg';
$filetype = wp_check_filetype( $file );

echo $filetype['ext'];  // output: jpg
echo $filetype['type']; // output: image/jpeg
0

#2 Check if the file extension is allowed on the site

To check, we get the file data (this don't check real MIME type of the file):

$filetype = wp_check_filetype( 'image.jpg' );

if( $filetype['ext'] )
	echo 'File with extension '. $filetype['ext'] .' is allowed';
else
	echo 'File with extension '. $filetype['ext'] .' is forbidden';
0

#3 Specifying permissible file types and checking

Let's specify the allowed file types in the array and check the file extension:

$mimes = array(
	'gif'   =>  'image/gif',
	'png'   =>  'image/png',
	'jpg|jpeg|jpe' => 'image/jpeg'
);

$file = 'image.bmp';

$filetype = wp_check_filetype( $file, $mimes );

if( $filetype['ext'] )
	echo 'allowed';
else
	echo 'banned';

Changelog

Since 2.0.4 Introduced.

wp_check_filetype() code WP 7.0

function wp_check_filetype( $filename, $mimes = null ) {
	if ( empty( $mimes ) ) {
		$mimes = get_allowed_mime_types();
	}
	$type = false;
	$ext  = false;

	foreach ( $mimes as $ext_preg => $mime_match ) {
		$ext_preg = '!\.(' . $ext_preg . ')$!i';
		if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
			$type = $mime_match;
			$ext  = $ext_matches[1];
			break;
		}
	}

	return compact( 'ext', 'type' );
}