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 |
|
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 |
【示例】:
- <?PHP
- function check_url($url){
- //解析url
- $url_pieces = parse_url($url);
- //设置正确的路径和端口号
- $path =(isset($url_pieces['path']))?$url_pieces['path']:'/';
- $port =(isset($url_pieces['port']))?$url_pieces['port']:'80';
- //用fsockopen()尝试连接
- if($fp =fsockopen($url_pieces['host'],$port,$errno,$errstr,30)){
- //建立成功后,向服务器写入数据
- $send = "HEAD $path HTTP/1.1 ";
- $send .= "HOST:$url_pieces['host'] ";
- $send .= "CONNECTION: CLOSE ";
- fwrite($fp,$send);
- //检索HTTP状态码
- $data = fgets($fp,128);
- //关闭连接
- fclose($fp);
- //返回状态码和类信息
- list($response,$code) = explode(' ',$data);
- if(code == 200){
- return array($code,'good');
- }else{
- return array($code,'bad');//数组第二个元素作为css类名
- }
- }else{
- //没有连接
- return array($errstr,'bad');
- }
- }
- //创建URL列表
- $urls = array(
- 'http://www.sdust.com',
- 'http://www.example.com'
- )
- //调整PHP脚本的时间限制:
- set_time_limit(0);//无限长时间完成任务
- //逐个验证url:
- foreach($urls as $url){
- list($code,$class) = check_url($url);
- echo "<p><a href ="$url">$url</a>(<span class ="$class">$code</span>)</p>";
- }
- ?>