file_is_displayable_image()WP 2.5.0

Validate that file is suitable for displaying within a web page.

1 time — 0.000001 sec (speed of light) | 50000 times — 0.42 sec (very fast) | PHP 7.2.16, WP 5.1.1
Hooks from the function

Return

true|false. True if suitable, false if not suitable.

Usage

file_is_displayable_image( $path );
$path(string) (required)
File path to test.

Examples

0

#1 Check if the files are an image

require_once ABSPATH . 'wp-admin/includes/image.php';

$path     = 'F:\server\sites\wp-test.ru\wp-admin\images\align-center.png';
$is_image = file_is_displayable_image( $path ); //> true

$path     = 'F:\server\sites\wp-test.ru\wp-admin\css\common.css';
$is_image = file_is_displayable_image( $path ); //> false

if ( $is_image ) {
	echo 'The file is an image';
}
else {
	echo 'The file is not an image';
}

Changelog

Since 2.5.0 Introduced.

file_is_displayable_image() code WP 6.4.3

function file_is_displayable_image( $path ) {
	$displayable_image_types = array( IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP, IMAGETYPE_ICO, IMAGETYPE_WEBP );

	$info = wp_getimagesize( $path );
	if ( empty( $info ) ) {
		$result = false;
	} elseif ( ! in_array( $info[2], $displayable_image_types, true ) ) {
		$result = false;
	} else {
		$result = true;
	}

	/**
	 * Filters whether the current image is displayable in the browser.
	 *
	 * @since 2.5.0
	 *
	 * @param bool   $result Whether the image can be displayed. Default true.
	 * @param string $path   Path to the image.
	 */
	return apply_filters( 'file_is_displayable_image', $result, $path );
}