How can file extensions be checked in PHP?
To check file extensions in PHP, you can use the pathinfo() function to get the file extension from a file path. This function returns an associative array with information about the file path, including the file extension. You can then compare the file extension to a list of allowed extensions to determine if it is valid.
$file_path = 'example.jpg';
$allowed_extensions = ['jpg', 'png', 'gif'];
$file_info = pathinfo($file_path);
$file_extension = $file_info['extension'];
if (in_array($file_extension, $allowed_extensions)) {
echo 'File extension is allowed';
} else {
echo 'File extension is not allowed';
}
Related Questions
- What are the best practices for using var_dump() or print_r() to display form input in an array in PHP?
- What are the recommended methods for handling complex data formats, like serialized PHP arrays or XML, to avoid compatibility issues in PHP applications?
- How can PHP be used to process form data and then forward it to a Perl script for further processing?