How can a custom function be created in PHP to extract and validate file extensions?

To create a custom function in PHP to extract and validate file extensions, you can use the pathinfo() function to extract the file extension from a given file path and then validate it against a list of allowed extensions. This function can help ensure that only files with specific extensions are processed or uploaded.

function validateFileExtension($file_path, $allowed_extensions) {
    $file_extension = pathinfo($file_path, PATHINFO_EXTENSION);
    
    if(in_array($file_extension, $allowed_extensions)) {
        return true;
    } else {
        return false;
    }
}

// Example usage
$file_path = "example.jpg";
$allowed_extensions = array("jpg", "png", "gif");
if(validateFileExtension($file_path, $allowed_extensions)) {
    echo "File extension is valid.";
} else {
    echo "Invalid file extension.";
}