编 写:袁 亮
时 间:2015-07-16
说 明:fsockopen初阶:了解并使用
一、作用(简单使用)
1、类似file_get_contents,curl,在程序中,发起一次网络请求,抓取数据或者调用接口等
2、curl能干的事,这个也都能干
3、在发起http请求的时候,会对http整个工作过程更熟悉,每一步都很清楚
二、工作流程
1、使用fsockopen打开一个网络连接或者一个Unix套接字连接
2、使用fwrite,传输请求头信息
3、使用fgets读取响应
4、使用fclose关闭套接字
ps:一个完整的http请求,更清晰些,平时访问网页的时候,浏览器帮我们做的这些工作
三、使用条件
1、php配置中开启 allow_url_fopen
四、简单范例,php.net
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)
\n";
} else {
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: www.example.com\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
五、函数封装
header("Content-Type:text/html;charset=utf-8;");
$data = fsockOpenHttp("http://local.ci123.com/yl/fsockopen/t.php",'POST',array('username'=>'yuanliang847','nickname'=>'暗夜御林'));
var_export($data);
//图片上传的暂未封装,可以自己看下firebug中上传图片时的请求信息,然后封装
function fsockOpenHttp($url, $method='GET', $postfields = NULL , $multi = false){
$url = trim($url);
if(!$url){
return array('status'=>4001,'mess'=>'链接不能为空');
}
$urlinfo = parse_url($url);
if(!$urlinfo['host']){
return array('status'=>4002,'mess'=>'链接非法,请填写完整链接地址');
}
if($urlinfo['scheme'] == 'https'){//判断是否是https请求
$port = 443;
$version = '1.1';
$host = 'ssl://'.$urlinfo['host'];
}else{
$port = 80;
$version = '1.0';
$host = $urlinfo['host'];
}
$urlinfo['path'] = $urlinfo['path']?$urlinfo['path']:'/';
$header = "{$method} {$urlinfo['path']} HTTP/$version\r\n";
$header .= "Host: {$urlinfo['host']}\r\n";
if($multi){
//$header .= "Content-Type: multipart/form-data; boundary=\r\n";
}else{
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
}
if(strtolower($method) == 'post' ){
if(is_array($postfields)){
$postfields = http_build_query($postfields);
}
$header .= "Content-Length: ".strlen($postfields)."\r\n";
$header .= "Connection: Close\r\n\r\n";
$header .= $postfields;
}else{
$header .= "Connection: Close\r\n\r\n";
}
$ret = '';
$fp = fsockopen($host,$port,$errno,$errstr,30);
if(!$fp){
return array('status'=>4003,'mess'=>'建立sock连接失败');
}
fwrite ($fp, $header);
while (!feof($fp)) {
$ret .= fgets($fp, 4096);
}
fclose($fp);
$info = split("\r\n\r\n",$ret);
$t = array_slice($info,1);
$returnInfo = implode('',$t);
$head = $info[0];
$tmp = split("\r\n", $head);
$tmp = split(" ", $tmp[0]);
$http_status = $tmp[1];
$html = iconv("utf-8","utf-8//ignore",$returnInfo);
return array(
'status' => '1',
'mess' => '请求成功',
'http_status'=> $http_status,//http响应头
'head' => $head,//完整返回头
'data' => $html//响应内容
);
}