What best practices should be followed when filtering file names in PHP to avoid unexpected results?

When filtering file names in PHP, it is crucial to sanitize the input to avoid unexpected results such as directory traversal attacks or file inclusion vulnerabilities. To prevent these issues, it is recommended to use functions like `basename()` to extract the filename from a path and remove any potentially harmful characters. Additionally, validating the file extension can help ensure that only allowed file types are accepted.

$filename = $_GET['filename']; // Example input from user

$filename = basename($filename); // Remove any directory traversal characters

$allowed_extensions = array("jpg", "png", "pdf"); // Define allowed file extensions

$extension = pathinfo($filename, PATHINFO_EXTENSION); // Get the file extension

if (!in_array($extension, $allowed_extensions)) {
    die("Invalid file type.");
}

// Further processing of the sanitized and validated filename