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 key components needed to create an effective nutrition diary system using PHP and SQL?
- How does the behavior of $_FILES['bild']['tmp_name'] vary across different PHP versions?
- What are best practices for ensuring compatibility of a 20-year-old PHP script with newer PHP versions like 7.3?