What are the best practices for handling file extensions in PHP scripts?

When handling file extensions in PHP scripts, it is important to validate and sanitize user input to prevent security vulnerabilities such as file inclusion attacks. One best practice is to use the pathinfo() function to extract the file extension from the filename and then compare it against a whitelist of allowed extensions. This helps ensure that only safe file types are processed by the script.

// Example of handling file extensions in PHP script

// Get the file extension using pathinfo()
$filename = 'example.jpg';
$extension = pathinfo($filename, PATHINFO_EXTENSION);

// Define a whitelist of allowed extensions
$allowedExtensions = ['jpg', 'png', 'gif'];

// Check if the file extension is in the whitelist
if (in_array($extension, $allowedExtensions)) {
    // Process the file
    echo "File extension is allowed";
} else {
    // Handle invalid file extension
    echo "Invalid file extension";
}