What are some best practices for handling file paths and extensions in PHP functions like filterfilename()?

When handling file paths and extensions in PHP functions like filterfilename(), it is important to sanitize user input to prevent security vulnerabilities such as directory traversal attacks. One way to do this is by using functions like basename() to extract the filename from a path and pathinfo() to get information about the file extension. Additionally, validating file extensions against a whitelist of allowed extensions can help prevent malicious file uploads.

function filterfilename($filename) {
    // Sanitize the filename to remove any potentially harmful characters
    $filename = basename($filename);

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

    // Whitelist of allowed file extensions
    $allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');

    // Check if the file extension is allowed
    if (!in_array($extension, $allowed_extensions)) {
        // Handle invalid file extension
        return false;
    }

    return $filename;
}