How to get favicon icons for any website in php

  6 months ago     Views:  412  
Jitesh Meniya
2 Follows


While working with my one of project, I needed to download favicon icon from different website. A favicon is shortcut icon or website icon or bookmark icon that is associated with particularly with that website. The favicon can also visible in addressbar of Web Browser. It can be also seen when you bookmark the website.

Mostly a favicon is stored as favicon.ico in root directory of website. A favicon is generated with the bellow link tag between <head> tags.

<link rel="shortcut icon" href="/favicon.ico" />

You cn get any website favicon when you run the website url:

www.anywebsite.com/favicon.ico 

But suppose downloading favicon from multiple website is time consuming and boring task. In that cases it is advise to make stuff automatic to save the time. Here is some of my solution for that.

Google's Shared Stuff

Google provides a Shared Stuff link that automatically retrieve the favicon image of any website. The basic url is:

https://www.google.com/s2/favicons?domain=hackthestuff.com

The domain GET parameter accepts website url for which you want to download favicon.

With this link, you can dynamically get favicon of any website. Here is my solution in PHP.

/**
 * download favicon from website
 *
 * @param $url string
 */
function get_favicon ($url) {

	$save_file_path = 'path/to/file/save/'

    $domain = parse_url($url)['host'];
    $filepath = $save_file_path . $url;

    if (!file_exists ($filepath)) {
        file_put_contents ($filepath, file_get_contents ('https://www.google.com/s2/favicons?domain=' . $domain));
    }

    return $filepath;
}

The above function will store favicon of any website to $save_file_path directory. Make sure you have enough permission to modify $save_file_path directory.

This way you can save to any website favicon.

Using faviconkit.com

One website faviconkit.com also provides free api to download favicon of any website. The get url to download favicon of any website is:

https://api.faviconkit.com/google.com/16

In this url, last two segment are website url and favicon size. With this link you can also get favicon of any website dynamically with programming language.

There are also many tools are available in the Github to download favicon for website. But for now, this is enough to download any website favicon.


Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

OR

No Comments