API Get Icon

自建获取网站图标 API

Favicon.php

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
<?php
namespace Jerrybendy\Favicon;


/**
 * Favicon 获取类
 *
 * ## 关于缓存:
 * 本来类库中是调用Redis来做缓存,后来想了下,还是让这个类只专注于自己的业
 * 务吧(获取图标)缓存这些操作交给外部来处理
 *
 * @author Jerry Bendy
 *
 * @link   http://blog.icewingcc.com
 *
 */

class Favicon
{

    /**
     * 是否使用调试模式,默认不启用
     * 可以通过修改此变量的值以启用调试,将会在控制台中
     * 或错误日志中输出一些运行相关的信息
     *
     * @var bool
     */
    public $debug_mode = false;


    /**
     * 保存传入的参数,其中:
     *
     *    origin_url:     保存传入的url参数的原始字符串信息
     *
     *
     *  以及一些额外的参数及暂存的数据
     */
    private $params = array();

    /**
     * 完整的形如  http://xxx.xxx.com:8888 这样的地址
     */
    private $full_host = '';

    /**
     * 包含获取到的最终的二进制数据
     *
     */
    private $data = NULL;

    /**
     * 最后一次请求花费的时间
     *
     * @var double
     */
    private $_last_time_spend = 0;

    /**
     * 最后一次请求消耗的内存
     *
     * @var string
     */
    private $_last_memory_usage = 0;

    /**
     * 文件映射,用于在规则匹配时直接返回内容
     *
     * @var array
     */
    private $_file_map = [];


    /**
     * 默认图标,如果设置了此文件将会在请求失败时返回这个图标
     *
     * @var string
     */
    private $_default_icon = '';


    /**
     * 获取网站Favicon并输出
     *
     * @param string $url    输入的网址
     *                       (The input URL)
     * @param bool   $return 是要求返回二进制内容还是直接显示它
     * @throws \InvalidArgumentException
     * @return string
     *
     */
    public function getFavicon($url = '', $return = FALSE)
    {

        /**
         * 验证传入参数
         */
        if (!$url) {
            throw new \InvalidArgumentException(__CLASS__ . ': Url cannot be empty', E_ERROR);
        }

        //
        $this->params['origin_url'] = $url;

        //解析URL参数
        $ret = $this->formatUrl($url);
        if (!$ret) {
            throw new \InvalidArgumentException(__CLASS__ . ': Invalided url', E_WARNING);
        }

        /**
         * 开始获取图标过程
         */
        $time_start = microtime(TRUE);

        $this->_log_message('Begin to get icon, ' . $url);


        /**
         * get the favicon bin data
         */
        $data = $this->getData();

        /**
         * 获取过程结束
         * 计算时间及内存的占用信息
         */
        $time_end = microtime(TRUE);
        $this->_last_time_spend = $time_end - $time_start;

        $this->_last_memory_usage = ((!function_exists('memory_get_usage')) ? '0' : round(memory_get_usage() / 1024 / 1024, 2)) . 'MB';

        $this->_log_message('Get icon complate, spent time ' . $this->_last_time_spend . 's, Memory_usage ' . $this->_last_memory_usage);

        /**
         * 设置输出Header信息
         * Output common header
         *
         */

        if ($data === FALSE && $this->_default_icon) {
            $data = @file_get_contents($this->_default_icon);
        }


        if ($return) {
            return $data;

        } else {

            if ($data !== FALSE) {

                foreach ($this->getHeader() as $header) {
                    @header($header);
                }

                echo $data;

            } else {
                header('Content-type: application/json');
                echo json_encode(array('status' => -1, 'msg' => 'Unknown Error'));
            }
        }

        return NULL;
    }


    /**
     * 获取输出 header
     * 2019 添加缓存时间
     *
     * @since v2.1
     * @return array
     */
    public function getHeader()
    {
        return array(
            'X-Robots-Tag: noindex, nofollow',
            'Content-type: image/x-icon',
          	'Cache-Control: public, max-age=604800'
        );
    }


    /**
     * 设置一组正则表达式到文件的映射,
     * 用于在规则匹配成功时直接从本地或指定的URL处获取内容并返回
     *
     * @param array $map 映射内容必须是   正则表达式  =>  文件路径  的数组,
     *                   文件通过 file_get_contents 函数读取,所以可以是本地文件或网络文件路径,
     *                   但必须要保证对应的文件是一定能被读取的
     * @return $this
     */
    public function setFileMap(array $map)
    {
        $this->_file_map = $map;

        return $this;
    }


    /**
     * @param string $filePath
     * @return $this
     */
    public function setDefaultIcon($filePath)
    {
        $this->_default_icon = $filePath;

        return $this;
    }


    /**
     * 获取最终的Favicon图标数据
     * 此为该类获取图标的核心函数
     *
     * @return bool|string
     */
    protected function getData()
    { 
        // 尝试匹配映射
        $this->data = $this->_match_file_map();

        //判断data中有没有来自插件写入的内容
        if ($this->data !== NULL) {
            $this->_log_message('Get icon from static file map, ' . $this->full_host);

            return $this->data;
        }

        //从网络获取图标

        //从源网址获取HTML内容并解析其中的LINK标签
        $html = $this->getFile($this->params['origin_url']);

        if ($html && $html['status'] == 'OK') {

            /*
             * 2016-01-31
             * FIX #1
             * 对取到的HTML内容进行删除换行符的处理,避免link信息折行导致的正则匹配失败
             */
            $html = str_replace(array("\n", "\r"), '', $html);

            //匹配完整的LINK标签,再从LINK标签中获取HREF的值
            if (@preg_match('/((<link[^>]+rel=.(icon|shortcut icon|alternate icon|apple-touch-icon)[^>]+>))/i', $html['data'], $match_tag)) {

                if (isset($match_tag[1]) && $match_tag[1] && @preg_match('/href=(\'|\")(.*?)\1/i', $match_tag[1], $match_url)) {

                    if (isset($match_url[2]) && $match_url[2]) {

                        //解析HTML中的相对URL 路径
                        $match_url[2] = $this->filterRelativeUrl(trim($match_url[2]), $this->params['origin_url']);

                        $icon = $this->getFile($match_url[2],true);

                        if ($icon && $icon['status'] == 'OK') {

                            $this->_log_message("Success get icon from {$this->params['origin_url']}, icon url is {$match_url[2]}");

                            $this->data = $icon['data'];
                        }
                    }
                }
            }
        }

        if ($this->data != NULL) {
            return $this->data;
        }

        //用来在第一次获取后保存可能的重定向后的地址
        $redirected_url = $html['real_url'];

        //未能从LINK标签中获取图标(可能是网址无法打开,或者指定的文件无法打开,或未定义图标地址)
        //将使用网站根目录的文件代替
        $data = $this->getFile($this->full_host . '/favicon.ico',true);

        if ($data && $data['status'] == 'OK') {
            $this->_log_message("Success get icon from website root: {$this->full_host}/favicon.ico");
            $this->data = $data['data'];

        } else {
            //如果直接取根目录文件返回了301或404,先读取重定向,再从重定向的网址获取
            $ret = $this->formatUrl($redirected_url);

            if ($ret) {
                //最后的尝试,从重定向后的网址根目录获取favicon文件
                $data = $this->getFile($this->full_host . '/favicon.ico',true);

                if ($data && $data['status'] == 'OK') {
                    $this->_log_message("Success get icon from redirect file: {$this->full_host}/favicon.ico");
                    $this->data = $data['data'];
                }

            }
        }
        
        /**
         * 从其他api最后获取图像 -----------------------------------------------------
         * 
         */
        // if ($this->data == NULL) {
        //     $thrurl='https://api.ooii.io/icon/api.php?url=';
        //     $icon = file_get_contents($thrurl.$this->full_host);  
        //     //$this->_log_message("--图标 md5 值为".md5($icon));
        //     if($icon && md5($icon)!="3ca64f83fdcf25135d87e08af65e68c9"){  //判断是否为对方 api 返回的默认图标,可通过上行 log 查看
        //         $this->_log_message("--从 {$thrurl} 获取到图标");
        //         $this->data = $icon; 
        //     } 
        // }
        

        if ($this->data == NULL) {
            //各个方法都试过了,还是获取不到。。。
            $this->_log_message("Cannot get icon from {$this->params['origin_url']}");

            return FALSE;
        }

        return $this->data;
    }



    /**
     * 解析一个完整的URL中并返回其中的协议、域名和端口部分
     * 同时会设置类中的parsed_url和full_host属性
     *
     * @param $url
     * @return bool|string
     */
    public function formatUrl($url)
    {
        /**
         * 尝试解析URL参数,如果解析失败的话再加上http前缀重新尝试解析
         *
         */
        $parsed_url = parse_url($url);

        if (!isset($parsed_url['host']) || !$parsed_url['host']) {
            //在URL的前面加上http://
            // add the prefix
            if (!preg_match('/^https?:\/\/.*/', $url))
                $url = 'http://' . $url;
            //解析URL并将结果保存到 $this->url
            $parsed_url = parse_url($url);

            if ($parsed_url == FALSE) {
                return FALSE;
            } else {
                /**
                 * 能成功解析的话就可以设置原始URL为这个添加过http://前缀的URL
                 */
                $this->params['origin_url'] = $url;
            }
        }

        $this->full_host = (isset($parsed_url['scheme']) ? $parsed_url['scheme'] : 'http') . '://' . $parsed_url['host'] . (isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '');

        return $this->full_host;
    }


    /**
     * 把从HTML源码中获取的相对路径转换成绝对路径
     *
     * @see 函数详情: http://blog.icewingcc.com/php-conv-addr-re-ab-2.html
     *
     * @param string $url HTML中获取的网址
     * @param string $URI 用来参考判断的原始地址
     * @return string 返回修改过的网址
     */
    private function filterRelativeUrl($url, $URI = '')
    {
        //STEP1: 先去判断URL中是否包含协议,如果包含说明是绝对地址则可以原样返回
        if (strpos($url, '://') !== FALSE) {
            return $url;
        }

        //STEP2: 解析传入的URI
        $URI_part = parse_url($URI);
        if ($URI_part == FALSE)
            return FALSE;

        $URI_root = $URI_part['scheme'] . '://' . $URI_part['host'] . (isset($URI_part['port']) ? ':' . $URI_part['port'] : '');

        //STEP3: 如果URL以左斜线开头,表示位于根目录

        // 如果URL以 // 开头,表示是省略协议的绝对路径,可以添加协议后返回
        if (substr($url, 0, 2) === '//') {
            return $URI_part['scheme'] . ':' . $url;
        }

        if (strpos($url, '/') === 0) {
            return $URI_root . $url;
        }

        //STEP4: 不位于根目录,也不是绝对路径,考虑如果不包含'./'的话,需要把相对地址接在原URL的目录名上
        $URI_dir = (isset($URI_part['path']) && $URI_part['path']) ? '/' . ltrim(dirname($URI_part['path']), '/') : '';
        if (strpos($url, './') === FALSE) {
            if ($URI_dir != '') {
                return $URI_root . $URI_dir . '/' . $url;
            } else {
                return $URI_root . '/' . $url;
            }
        }

        //STEP5: 如果相对路径中包含'../'或'./'表示的目录,需要对路径进行解析并递归
        //STEP5.1: 把路径中所有的'./'改为'/','//'改为'/'
        $url = preg_replace('/[^\.]\.\/|\/\//', '/', $url);
        if (strpos($url, './') === 0)
            $url = substr($url, 2);

        //STEP5.2: 使用'/'分割URL字符串以获取目录的每一部分进行判断
        $URI_full_dir = ltrim($URI_dir . '/' . $url, '/');
        $URL_arr = explode('/', $URI_full_dir);

        // 这里为了解决有些网站在根目录下的文件也使用 ../img/favicon.ico 这种形式的错误,
        // 对这种本来不合理的路径予以通过, 并忽略掉前面的两个点 (没错, 我说的是 gruntjs 的官网)
        if ($URL_arr[0] == '..') {
            array_shift($URL_arr);
        }

        //因为数组的第一个元素不可能为'..',所以这里从第二个元素可以循环
        $dst_arr = $URL_arr;  //拷贝一个副本,用于最后组合URL
        for ($i = 1; $i < count($URL_arr); $i++) {
            if ($URL_arr[$i] == '..') {
                $j = 1;
                while (TRUE) {
                    if (isset($dst_arr[$i - $j]) && $dst_arr[$i - $j] != FALSE) {
                        $dst_arr[$i - $j] = FALSE;
                        $dst_arr[$i] = FALSE;
                        break;
                    } else {
                        $j++;
                    }
                }
            }
        }

        //STEP6: 组合最后的URL并返回
        $dst_str = $URI_root;
        foreach ($dst_arr as $val) {
            if ($val != FALSE)
                $dst_str .= '/' . $val;
        }

        return $dst_str;
    }



    /**
     * 从指定URL获取文件
     * 2019 添加请求内容判断
     * 
     * @param string $url
     * @param bool   $isimg 是否为图片
     * @param int    $timeout 超时值,默认为10秒
     * @return string 成功返回获取到的内容,同时设置 $this->content,失败返回FALSE
     */
    private function getFile($url, $isimg = false, $timeout = 2)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        /*
         * 2019-06-20
         * 修复ssl的错误
         */
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FAILONERROR, 1);
        //执行重定向获取
        $ret = $this->curlExecFollow($ch, 2);

        if($isimg){
            $mime=curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
            $mimeArray=explode('/',$mime);
        }
        $arr = array(
            'status'   => 'FAIL',
            'data'     => '',
            'real_url' => ''
        );
        if(!$isimg ||  $mimeArray[0] == 'image'){
            if ($ret != false) {
                $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

                $arr = array(
                    'status'   => ($status >= 200 && $status <= 299) ? TRUE : FALSE,
                    'data'     => $ret,
                    'real_url' => curl_getinfo($ch, CURLINFO_EFFECTIVE_URL)
                );

            }
            curl_close($ch);

            return $arr;
        }else{
            $this->_log_message("不是图片:{$url}");
            return $arr;
        }
    }



    /**
     * 使用跟综重定向的方式查找被301/302跳转后的实际地址,并执行curl_exec
     * 代码来自: http://php.net/manual/zh/function.curl-setopt.php#102121
     *
     * @param resource $ch          CURL资源句柄
     * @param int      $maxredirect 最大允许的重定向次数
     * @return string
     */
    private function curlExecFollow( &$ch, $maxredirect = null) { 
        $mr = $maxredirect === null ? 5 : intval($maxredirect); 
        if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) { 
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $mr > 0); 
            curl_setopt($ch, CURLOPT_MAXREDIRS, $mr); 
        } else { 
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); 
            if ($mr > 0) { 
                $newurl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); 
    
                $rch = curl_copy_handle($ch); 
                curl_setopt($rch, CURLOPT_HEADER, true); 
                curl_setopt($rch, CURLOPT_NOBODY, true); 
                curl_setopt($rch, CURLOPT_NOSIGNAL, 1);
                curl_setopt($rch, CURLOPT_CONNECTTIMEOUT_MS, 800); 
                curl_setopt($rch, CURLOPT_FORBID_REUSE, false); 
                curl_setopt($rch, CURLOPT_RETURNTRANSFER, true); 
                do { 
                    curl_setopt($rch, CURLOPT_URL, $newurl); 
                    $header = curl_exec($rch); 
                    if (curl_errno($rch)) { 
                        $code = 0; 
                    } else { 
                        $code = curl_getinfo($rch, CURLINFO_HTTP_CODE); 
                        if ($code == 301 || $code == 302) { 
                            preg_match('/Location:(.*?)\n/', $header, $matches); 
                            $newurl = trim(array_pop($matches)); 
                            /**
                             * 这里由于部分网站返回的 Location 的值可能是相对网址, 所以还需要做一步
                             * 转换成完整地址的操作
                             *
                             * @since v2.2.2
                             */
                            $newurl = $this->filterRelativeUrl($newurl, $this->params['origin_url']);
                        } else { 
                            $code = 0; 
                        } 
                    } 
                } while ($code && --$mr); 
                curl_close($rch); 
                if (!$mr) { 
                    if ($maxredirect === null) { 
                        trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING); 
                    } else { 
                        $maxredirect = 0; 
                    } 
                    return false; 
                } 
                curl_setopt($ch, CURLOPT_URL, $newurl); 
            } 
        } 
        return curl_exec($ch); 
    } 

    /**
     * 在设定的映射条件中循环并尝试匹配每一条规则,
     * 在条件匹配时返回对应的文件内容
     *
     * @return null|string
     */
    private function _match_file_map()
    {
        foreach ($this->_file_map as $rule => $file) {
            if (preg_match($rule, $this->full_host)) {
                return @file_get_contents($file);
            }
        }

        return NULL;
    }


    /**
     * 如果开启了调试模式,将会在控制台或错误日志中输出一些信息
     *
     * @param $message
     */
    private function _log_message($message)
    {
        if ($this->debug_mode) {
            error_log(date('d/m/Y H:i:s : ').$message.PHP_EOL,3, "./my-errors.log");
        }
    }

}

get.php

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
<?php

// 如果自用,可加个密码
// $auth = isset($_GET['auth']) ? $_GET['auth'] : '';
// define('AUTH', true);
// define('AUTH_SECRET', 'jinitaimei'); //设定鉴权密码
// if (AUTH) {
//     if ($auth == '' || $auth != AUTH_SECRET) {
//         // 直接返回403
//         // http_response_code(403);
//         // echo '😵出错了!缺少参数:auth';
//         // exit;
//         // 或者输出一张图片
//         header('content-type:image/png;');
//         header('Location:https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.huabanimg.com%2F31d4ecf35a14b1269b987e1326d1369534b6f6cc4f757-oAIvsv_fw658&refer=http%3A%2F%2Fhbimg.huabanimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1649818489&t=d742b9b604af14f375d4c22b6f5cb9b0');
//     }
// }

if( !isset($_GET['url'])){
    return http_response_code(404);
}

require "./Favicon.php";

$favicon = new \Jerrybendy\Favicon\Favicon;


/* ------ 参数设置 ------ */

$defaultIco='favicon.png';   //默认图标路径
$expire = 2592000;           //缓存有效期30天, 单位为:秒,为0时不缓存

/* ------ 参数设置 ------ */



/**
 * 设置默认图标
 */
$favicon->setDefaultIcon($defaultIco);

/**
 * 检测URL参数
 */
$url = $_GET['url'];

/*
 * 格式化 URL, 并尝试读取缓存
 */
$formatUrl = $favicon->formatUrl($url);

if($expire == 0){
    $favicon->getFavicon($formatUrl, false);
    exit;
}
else{
    $defaultMD5 = md5(file_get_contents($defaultIco));
    
    $data = Cache::get($formatUrl,$defaultMD5,$expire);
    if ($data !== NULL) {
        foreach ($favicon->getHeader() as $header) {
            @header($header);
        }
        echo $data;
        exit;
    }

    /**
     * 缓存中没有指定的内容时, 重新获取内容并缓存起来
     */
    $content = $favicon->getFavicon($formatUrl, TRUE);
    
    if( md5($content) == $defaultMD5 ){
        $expire = 43200; //如果返回默认图标,设置过期时间为12小时。Cache::get 方法中需同时修改
    }

    Cache::set($formatUrl, $content, $expire);

    foreach ($favicon->getHeader() as $header) {
        @header($header);
    }

    echo $content;
    exit;
}

$type=$_GET['type'];
switch ($type) {   
    //Json格式解析
    case 'json':
    $result = array (
        'state' => 200,
        'iconurl' => $iconurl
        );
    header('Content-type:text/json');
    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
    header('Access-Control-Allow-Methods: GET, POST, PUT');
    echo json_encode($result);  
    break;
    //IMG
    default:
    header('content-type:image/png;');
    header("Location:".$result['iconurl']);
    break;
}

/**
 * 缓存类
 */
class Cache
{
    /**
     * 获取缓存的值, 不存在时返回 null
     *
     * @param $key
     * @param $default  默认图片
     * @param $expire   过期时间
     * @return string
     */
    public static function get($key, $default, $expire)
    {
        $dir = 'cache'; //图标缓存目录
       
        //$f = md5( strtolower( $key ) );
        $f = parse_url($key)['host'];

        $a = $dir . '/' . $f . '.txt';

        if(is_file($a)){
            $data = file_get_contents($a);
            if( md5($data) == $default ){
                $expire = 43200; //如果返回默认图标,过期时间为12小时。
            }
            if( (time() - filemtime($a)) > $expire ){
                return null;
            }
            else{
                return $data;
            }
		}
        else{
            return null;
        }
    }

    /**
     * 设置缓存
     *
     * @param $key
     * @param $value
     * @param $expire   过期时间
     */
    public static function set($key, $value, $expire)
    {
        $dir = 'cache'; //图标缓存目录
        
        //$f = md5( strtolower( $key ) );
        $f = parse_url($key)['host'];

        $a = $dir . '/' . $f . '.txt';
        
        //如果缓存目录不存在则创建
        if (!is_dir($dir)) mkdir($dir,0777,true) or die('创建缓存目录失败!');

        if ( !is_file($a) || (time() - filemtime($a)) > $expire ) {
            $imgdata = fopen($a, "w") or die("Unable to open file!");  //w  重写  a追加
            fwrite($imgdata, $value);
            fclose($imgdata); 
        }
    }
}

使用格式:/get.php?url=