Are there any potential pitfalls when using pathinfo or SplFileInfo to get the file extension of an image URL in PHP?

When using pathinfo or SplFileInfo to get the file extension of an image URL in PHP, a potential pitfall is that the URL may not actually point to a file on the server. To solve this, you can first check if the URL exists and is a valid file before attempting to extract the file extension.

$url = 'https://www.example.com/image.jpg';

if (filter_var($url, FILTER_VALIDATE_URL)) {
    $file_headers = @get_headers($url);
    if ($file_headers && strpos($file_headers[0], '200')) {
        $path_parts = pathinfo($url);
        $extension = $path_parts['extension'];
        echo $extension;
    } else {
        echo 'Invalid URL or file does not exist.';
    }
} else {
    echo 'Invalid URL.';
}