Socket可以理解为两台计算机相互通信的通道。
用法:使用fsockopen()函数
具体用法详见上篇文章。函数的参数为URL、端口号、一个存放错误编号的变量、一个存放错误信息字符串的变量和超时等待时间。(只有第一个参数是必须的)
常见的端口:
21(FTP)
22(SSH)
23(Telnet)
25(SMTP)
80(Web)
110(POP)
3306(MySql)
其中,组成URl的几个部分为:协议名scheme
,主机host
,端口号port
,文件路径path
,查询参数query
。
当url是http://www.example.com/view.php?week=1#demo
时:
Scheme:http
Host:www.example.com
Port:80
Path:View
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\r\n";
$send .= "HOST:$url_pieces['host']\r\n";
$send .= "CONNECTION: CLOSE\r\n\r\n";
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>";
}
?>
使用fsockopen()
函数比fopen()
函数的优点:
fopen()
只会在PHP
中已经将allow_url_fopen
设置为真时才能使用,而fsockopen()
并没有限制。
本文摘自:http://www.cnblogs.com/baocheng/p/5902560.html
