How to detect favicon (shortcut icon) for any site via php?

How to detect favicon (shortcut icon) for any site using php?

I cannot write regexp because it is different on sites.

+4
source share
3 answers

You can use this address and drop it into regex

http://www.google.com/s2/favicons?domain=www.example.com

This fixes the problem you encountered with Regexp and different results for the domain

+14
source

You can request http://domain.com/favicon.ico using PHP and see if you have 404.

If you get 404, you can pass the DOM of the site by looking for a different location, as indicated in the head element by the link element, with rel="icon" .

 // Helper function to see if a url returns `200 OK`. function $resourceExists($url) { $headers = get_headers($request); if ( ! $headers) { return FALSE; } return (strpos($headers[0], '200') !== FALSE); } function domainHasFavicon($domain) { // In case they pass 'http://example.com/'. $request = rtrim($domain, '/') . '/favicon.ico'; // Check if the favicon.ico is where it usually is. if (resourceExists($request)) { return TRUE; } else { // If not, we'll parse the DOM and find it $dom = new DOMDocument; $dom->loadHTML($domain); // Get all `link` elements that are children of `head` $linkElements = $dom ->getElementsByTagName('head') ->item(0) ->getElementsByTagName('link'); foreach($linkElements as $element) { if ( ! $element->hasAttribute('rel')) { continue; } // Split the rel up on whitespace separated because it can have `shortcut icon`. $rel = preg_split('/\s+/', $element->getAttribute('rel')); if (in_array('link', $rel)) { $href = $element->getAttribute('href'); // This may be a relative URL. // Let assume http, port 80 and Apache $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; if (substr($href, 0, strlen($url)) !== $url) { $href = $url . $href; } return resourceExists($href); } } return FALSE; } 

If you want the url to be returned in favicon.ico , it is trivial to modify the function above.

+1
source
 $address = 'http://www.youtube.com/' $domain = parse_url($address, PHP_URL_HOST); 

or from the database

 $domain = parse_url($row['address_column'], PHP_URL_HOST); 

display with

 <image src="http://www.google.com/s2/favicons?domain='.$domain.'" /> 
+1
source

All Articles