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
- How can PHP be used to create a coordinate grid and display images at specific positions?
- How can the use of while loops in PHP be optimized for better performance and efficiency when working with MySQL data?
- Are there any German hosting providers that offer FTP servers with trigger support for initiating scripts upon file upload, and how reliable is this feature in practice?