sock

Socket可以理解为两台计算机相互通信的通道。

用法:使用fsockopen()函数

具体用法详见上篇文章。函数的参数为URL、端口号、一个存放错误编号的变量、一个存放错误信息字符串的变量和超时等待时间。(只有第一个参数是必须的)

常见的端口表:

端口号

主要用途

21

FTP

22

SSH

23

Telnet

25

SMTP

80

Web

110

POP

其中,组成URl的几个部分为:协议名(scheme),主机(host),端口号(port),文件路径(path),查询参数(query)。

当url是http://www.example.com/view.php?week=1#demo时:

指标

Scheme

http

Host

www.example.com

Port

80

User

 

Pass

 

Path

View.php

Query

Week=1

Fragment

#demo

常见的HTTP状态码:

代码

含义

200

OK

204

NO Content

400

Bad Request

401

Unauthorized

403

Forbidden

404

Not Found

408

Time out

5**

Server error

【示例】:

  1. <?PHP  
  2.        function check_url($url){  
  3.               //解析url  
  4.               $url_pieces = parse_url($url);  
  5.               //设置正确的路径和端口号  
  6.               $path =(isset($url_pieces['path']))?$url_pieces['path']:'/';  
  7.               $port =(isset($url_pieces['port']))?$url_pieces['port']:'80';  
  8.               //用fsockopen()尝试连接  
  9.               if($fp =fsockopen($url_pieces['host'],$port,$errno,$errstr,30)){  
  10.                      //建立成功后,向服务器写入数据  
  11.                      $send = "HEAD $path HTTP/1.1 ";  
  12.                      $send .= "HOST:$url_pieces['host'] ";  
  13.                      $send .= "CONNECTION: CLOSE ";  
  14.                      fwrite($fp,$send);  
  15.                      //检索HTTP状态码  
  16.                      $data = fgets($fp,128);  
  17.                      //关闭连接  
  18.                      fclose($fp);  
  19.                      //返回状态码和类信息  
  20.                      list($response,$code) = explode(' ',$data);  
  21.                      if(code == 200){  
  22.                             return array($code,'good');  
  23.                      }else{  
  24.                             return array($code,'bad');//数组第二个元素作为css类名  
  25.                      }  
  26.               }else{  
  27.                      //没有连接  
  28.                      return array($errstr,'bad');  
  29.               }  
  30.                
  31.        }  
  32.        //创建URL列表  
  33.        $urls = array(  
  34.               'http://www.sdust.com',  
  35.               'http://www.example.com'  
  36.        )  
  37.        //调整PHP脚本的时间限制:  
  38.        set_time_limit(0);//无限长时间完成任务  
  39.        //逐个验证url:  
  40.        foreach($urls as $url){  
  41.               list($code,$class) = check_url($url);  
  42.               echo "<p><a href ="$url">$url</a>(<span class ="$class">$code</span>)</p>";  
  43.                
  44.        }  
  45. ?> 
原文地址:https://www.cnblogs.com/hehexu/p/8667879.html