Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if a url is an image url with php?

I need to check the url is image url or not? How can i do this?

Examples :

  • http://www.google.com/ is not an image url.
  • http://www.hoax-slayer.com/images/worlds-strongest-dog.jpg is an image url.
  • https://stackoverflow.com/search?q=.jpg is not an image url.
  • http://www.google.com/profiles/c/photos/private/AIbEiAIAAABECK386sLjh92M4AEiC3ZjYXJkX3Bob3RvKigyOTEzMmFmMDI5ODQ3MzQxNWQxY2VlYjYwYmE2ZTA4YzFhNDhlMjBmMAEFQ7chSa4PMFM0qw02kilNVE1Hpw is an image url.
like image 460
Giffary Avatar asked Aug 08 '10 08:08

Giffary


People also ask

How do you check if an URL is an image?

To check if a url is an image, call the test() method on a regular expression that matches an image extension at the end of a string, e.g. . png or . jpg . The test() method will check if the url ends with an image extension and will return true if it does.

How do you check if a file is an image in PHP?

Using file extension and getimagesize function to detect if uploaded file has right format is just the entry level check and it can simply bypass by uploading a file with true extension and some byte of an image header but wrong content.

How can I check if a URL is available in PHP?

Existence of an URL can be checked by checking the status code in the response header. The status code 200 is Standard response for successful HTTP requests and status code 404 means URL doesn't exist.


2 Answers

Here is a way that requires curl, but is faster than getimagesize, as it does not download the whole image. Disclaimer: it checks the headers, and they are not always correct.

function is_url_image($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_NOBODY, 1);
        $output = curl_exec($ch);
        curl_close($ch);

        $headers = array();
        foreach(explode("\n",$output) as $line){
            $parts = explode(':' ,$line);
            if(count($parts) == 2){
                $headers[trim($parts[0])] = trim($parts[1]);
            }

        }

        return isset($headers["Content-Type"]) && strpos($headers['Content-Type'], 'image/') === 0;
    }
like image 75
nikksan Avatar answered Sep 30 '22 08:09

nikksan


If you want to be absolutely sure, and your PHP is enabled for remote connections, you can just use

getimagesize('url');

If it returns an array, it is an image type recognized by PHP, even if the image extension is not in the url (per your second link). You have to keep in mind that this method will make a remote connection for each request, so perhaps cache urls that you already probed in a database to lower connections.

like image 29
Blizz Avatar answered Sep 30 '22 10:09

Blizz