PHP - getting a site's favicon and converting it to png if necessary

后端 未结 6 475
醉梦人生
醉梦人生 2020-12-28 22:57

For any given site \"example.domain.tld\" or merely \"domain.tld\" I need to do the following in PHP:

  • If the site has a favicon, get it wherever it is
相关标签:
6条回答
  • 2020-12-28 23:35

    Coverting to PNG is not that hard.

    I don't get the question entirely, is this fav icon on your site or on other sites? If on other sites, you will have to parse fetched HTML and then somehow load favicon.

    0 讨论(0)
  • 2020-12-28 23:39

    As Iain Fraser said, the Favicon class from controlstyle.com doesn't works with all test case.

    Basically, if provided, the <link> shortcut icon tag can contain different URL types :

    • full absolute URL : http://www.domain.com/images/fav.ico
    • absolute URL with relative scheme : //www.domain.com/images/fav.ico
    • absolute path : /images/fav.ico
    • relative URL : ../images/fav.ico

    Furthermore, the web page can contain a <base href="..." /> attribute that changes how to deal with relative URL and absoute path...

    So I've written a PHP class that works with all these cases. First, it tries to get the favicon URL from the <link> attribute, and fallback to the default favicon URI (//www.domain.com/favicon.ico) in case of failure.

    You can grab it on my website here : http://www.finalclap.com/faq/477-php-favicon-find-download or install it using composer : composer require vincepare/favicon-downloader.

    How to use :

    <?php
    require 'FaviconDownloader.class.php';
    $favicon = new FaviconDownloader('http://stackoverflow.com/questions/19503326/bug-with-chrome-tabs-create-in-a-loop');
    
    if($favicon->icoExists){
        echo "Favicon found : ".$favicon->icoUrl."\n";
    
        // Saving favicon to file
        $filename = 'favicon-'.time().'.'.$favicon->icoType;
        file_put_contents($filename, $favicon->icoData);
        echo "Saved to ".$filename."\n\n";
    } else {
        echo "No favicon for ".$favicon->url."\n\n";
    }
    ?>
    
    0 讨论(0)
  • 2020-12-28 23:40

    Found this: http://www.controlstyle.com/articles/programming/text/php-favicon/

    I'm about to try it for my project and I'll report back and tell you if it works!

    Cheers

    Iain

    0 讨论(0)
  • 2020-12-28 23:45

    If the favicon isn't located at /favicon.ico I guess you have to parse the HTML.

    For the filetype detection, you can use this extension, which detects the filetype by using magic bytes.

    You can convert to PNG by using the GD library, an example can be found here.

    0 讨论(0)
  • 2020-12-28 23:46

    As is typical, I found a passable solution shortly after asking the question - let google do the work for you:

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

    returns a 16x16 png

    0 讨论(0)
  • 2020-12-28 23:53

    If your PHP install includes the GD library, you can convert an image to a PNG using the imagepng function.

    0 讨论(0)
提交回复
热议问题