Home  >  Article  >  php教程  >  PHP获取网站图标(favicon.ico)文件

PHP获取网站图标(favicon.ico)文件

WBOY
WBOYOriginal
2016-06-06 19:36:213283browse

有的 网站 源码中加入了这几行代码: 1 link rel ="shortcut icon" href ="/favicon.ico" type ="image/x-icon" / 或者是 1 link rel =" icon" href ="/favicon.ico" type ="image/x-icon" / 这样可以指定 图标 位置存放。 但现在的浏览器大多支持自动 获取

  有的网站源码中加入了这几行代码:

<span>1</span> <span><span>link </span><span>rel</span><span>="shortcut icon"</span><span> href</span><span>="/favicon.ico"</span><span> type</span><span>="image/x-icon"</span> <span>/></span></span>

  或者是

<span>1</span> <span><span>link </span><span>rel</span><span>=" icon"</span><span> href</span><span>="/favicon.ico"</span><span> type</span><span>="image/x-icon"</span> <span>/></span></span>

  这样可以指定图标位置存放。

  但现在的浏览器大多支持自动获取网站根目录下的.ico文件,所以源码中看不到那几行代码。

  可行的方法:

  

<span> 1</span>             <span>//</span><span>得到每一个url,<strong>获取</strong>其中的icon</span>
<span> 2</span>             <span>$url</span> = <span>$matches</span>[1][<span>$i</span><span>];
</span><span> 3</span>             <span>$contents</span> = @<span>file_get_contents</span>(<span>$url</span><span>); 
</span><span> 4</span>             <span>preg_match</span>('/<link rel=".*?icon" .>/', <span>$contents</span>,<span>$icon</span><span>);
</span><span> 5</span>             <span>if</span>(!<span>empty</span>(<span>$icon</span><span>)){
</span><span> 6</span>                 <span>//</span><span> print_r($icon[1]);</span>
<span> 7</span>                 <span>echo</span> "<br>"<span>;
</span><span> 8</span>                 <span>$array</span> = @<span>get_headers</span>(<span>$icon</span>[1],1<span>); 
</span><span> 9</span>                 <span>if</span>(<span>preg_match</span>('/200/',<span>$array</span>[0<span>])){ 
</span><span>10</span>                     <span>//</span><span> echo "<pre class="brush:php;toolbar:false">
"; 11 print_r($icon[1]); 12 echo "PHP获取网站图标(favicon.ico)文件; 13 // echo "string"; 14 // print_r($array); 15 }else{ 16 //去掉多余的斜杠 17 $url = substr_replace($url,"",-1); 18 echo "无效url资源!".$url.$icon[1]; 19 echo "PHP获取网站图标(favicon.ico)文件; 20 } 21 22 }else{ 23 //这里笔者试了很多种方法,后来发现通过url可以入手,从url截取网址的根目录,由于习惯性的把文件名名为favicon.ico,所以可以直接访问类似这样的url得到图标文件,http://wenwen.sogou.com/favicon.ico 24 $url=substr($url,7);//去除前面 25 $position = strpos($url, '/'); 26 $url=substr($url,0,$position); 27 echo "PHP获取网站图标(favicon.ico)文件; 28 // echo $url."/favicon.ico
";
29 //判断网站的根目录是否存在.icon文件 30 // $url='http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]; 31 // echo dirname($url); 32 // if(file_exists("favicon.ico")) 33 // echo "

存在

";
34 }

  思路:

    先判断源码中是否有那几行添加iocn的代码,如果有就直接抓取代码,再判断是否为有效的url,然后再判断显示,没有则获取根目录后显示。

   

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn