使用PHP抓取网站ico图标

网站许久没用更新,以后会经常更新,本次分享一个使用PHP抓取网站ico的程序,提供一个网站列表后对网站的ico进行下载抓取,具体代码如下:

<?php
/**
* 更新热站ico
* gao 2015-03-24
*/

error_reporting(0);

// 加载ICO抓取名单,需要区分HTTP和HTTPS类型网站,一行一个网站
// 如:http://yun.baidu.com https://wx.qq.com
$handle = fopen('site.txt', 'r');

if($handle)
{
    $success_ico = array();
    $faild_ico   = array();
    $count       = 0;
    
    unlink('success.ico.txt');
    unlink('faild.ico.txt');
    
    while( ($url = fgets($handle, 4096)) !== false )
    {
        $count++;
        $url    = trim($url);        
        $scheme = parse_url($url, PHP_URL_SCHEME);
        $host   = parse_url($url, PHP_URL_HOST);
        
        if(file_exists("ico/{$host}.ico"))
        {
            file_put_contents('success.ico.txt',  $url . PHP_EOL, FILE_APPEND);
            echo "N{$count} [continue] {$host}.ico" . PHP_EOL;
            continue;
        }
        
        $ico    = curl_get("{$scheme}://{$host}/favicon.ico");
        
        if(!is_ico_image($ico))
        {
            // 抓取首页匹配是否有自定义ICO
            $ico_html = curl_get("{$scheme}://{$host}/");
            preg_match('/href=\"(.*?)\.ico/i', $ico_html, $match);
            // 匹配HTTP/HTTPS类型ICO,匹配相对路径和绝对路径ICO
            if($match[1])
            {
                $url = substr($match[1], 0, 4) == 'http' ? $match[1] : $scheme . '://' . $host . $match[1];
                $url.= '.ico';
                $ico = curl_get($url);
            }
        }
        
        if(is_ico_image($ico))
        {
            file_put_contents("ico/{$host}.ico", $ico);
            file_put_contents('success.ico.txt',  $url . PHP_EOL, FILE_APPEND);
            echo "N{$count} [success] {$host}.ico" . PHP_EOL;
        }
        else
        {
            file_put_contents('faild.ico.txt',  $url . PHP_EOL, FILE_APPEND);
            echo "N{$count} [faild] {$host}.ico" . PHP_EOL;
        }
    }
    
    fclose ($handle);
    
}

// 判断是否是图片,可能是404页面
function is_ico_image($ico)
{
    if($ico)
    {
        file_put_contents('ico_tmp/favicon.ico', $ico);
        $type = getimagesize('ico_tmp/favicon.ico');
        unlink('ico_tmp/favicon.ico');
        if($type)
        {
            return true;
        }
    }
    return false;
}

// 使用curl模拟GET抓取网站ico信息
function curl_get($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_HEADER, false);  // 不需要header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 不自动输出  
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:8.8.8.8', 'CLIENT-IP:8.8.8.8'));  // 模拟header
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11");
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 设置每个请求的超时时间
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

实例下载地址 : http://pan.baidu.com/s/1bnxumzt