Search code examples
phpfile-exists

php how to get image from url without knowing extension


I would like to retrieve an image from a given url, i have the filename but the issue i have is that the extension is unknown. It could be either, jpg, gif or png.

This is how i have approached it but doesnt seem to be working:

$extensions = array('jpg', 'png', 'gif');
    foreach ($extensions as $ext) {
        if (file_exists('https://mytestimage.com/products/3c763dce-666b-4ba9-a05a-cca846391aea/thumb.' . $ext)) {
            echo 'Found filename.' . $ext;
            break;
        }
    }

Any suggestions?


Solution

  • Since the file is off-site, check if the URL exists instead.

    $file = 'http://example.com/image.jpg';
    $fileHeaders = @get_headers($file);
    if( $fileHeaders[0]=='HTTP/1.1 404 Not Found')
    {
        // File doesn't exist
    }
    else
    {
        // File exists
    }
    

    You can apply this logic to your loop for the different extensions.

    References: PHP.net & SO