wp_check_filetype()WP 2.0.4

Retrieve the file type from the file name.

You can optionally define the mime array, if needed.

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

No Hooks.

Return

Array. Values for the extension and mime type.

Usage

wp_check_filetype( $filename, $mimes );
$filename(string) (required)
File name or path.
$mimes(string[])
Array of allowed mime types keyed by their file extension regex.
Default: null

Examples

0

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

Code of wp_check_filetype() WP 6.0.1

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' );
}