The file_is_valid_image() WordPress PHP function is used to validate if a given file is an image.
Usage
To use the file_is_valid_image() function, pass a string representing the file path as the argument. If the file at the specified path is a valid image, the function will return true. Otherwise, it will return false.
// Checks if the file is a valid image $isValid = file_is_valid_image('/path/to/your/image.jpg'); // Outputs: true or false echo $isValid;
Parameters
- $path (string) – The file path of the image to validate.
More information
See WordPress Developer Resources: file_is_valid_image()
Examples
Validate a JPEG Image
In this example, we are validating a JPEG image. If the image is valid, it will output ‘true’.
$path = '/path/to/your/image.jpg'; $isValid = file_is_valid_image($path); echo $isValid; // Outputs: true or false
Validate a PNG Image
This example shows how to validate a PNG image.
$path = '/path/to/your/image.png'; $isValid = file_is_valid_image($path); echo $isValid; // Outputs: true or false
Validate a Non-existent Image
This example demonstrates how the function behaves when the image does not exist. It should return false.
$path = '/path/to/your/nonexistent.jpg'; $isValid = file_is_valid_image($path); echo $isValid; // Outputs: false
Validate a Non-image File
In this example, we are validating a text file. As a text file is not an image, it should return false.
$path = '/path/to/your/file.txt'; $isValid = file_is_valid_image($path); echo $isValid; // Outputs: false
Validate an Image with Uppercase Extension
This example demonstrates how to validate an image file with an uppercase extension. The function treats file extensions case-insensitively.
$path = '/path/to/your/image.JPG'; $isValid = file_is_valid_image($path); echo $isValid; // Outputs: true or false