fsockopen 是一个非常强大的函数,支持socket编程,可以使用fsockopen实现邮件发送等socket程序等等,使用fcockopen需要自己手动拼接出header部分。具体可以参考官方文档: http://cn2.php.net/fsockopen/。
resource fsockopen ( string $hostname [, int $port = -1 [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") ]]]] )
fsockopen — Open Internet or Unix domain socket connection 打开网络的 Socket 链接。
目前这个函数提供两个 Socket 文件流使用方式,分别为 Internet 用的 AF_INET 及 Unix 用的 AF_UNIX。
当在 Internet 情形下使用时,参数 hostname 及 port 分别代表网址及埠号。
在 UNIX 情形可做 IPC,hostname 参数表示到 socket 的路径,port 配置为 0。
可省略的 timeout 选项表示多久没有连上就中断。在使用本函数之后会返回文件指针,供文件函数使用,包括 fgets()、fgetss()、fputs()、fclose() 与 feof()。参数 errno 及 errstr 也是可省略的,主要当做错误处理使用。使用本函数,会使用搁置模式 (blocking mode) 处理,可用 set_socket_blocking() 转换成无搁置模式。
下面用 fsockopen 来模拟生成 HTTP 连接。
fsockopen 除了前面小节的模拟生成 HTTP 连接之外,还能实现很多功能,比如模拟 post 和 get 传送数据的方法。比如下面的例子:
$fp = fsockopen("www.cnblogs.com", 80, $errno, $errstr, 30);if (!$fp)
{echo "$errstr ($errno)
\n";
}else{$out = "GET / HTTP/1.1\r\n";$out .= "Host: www.cnblogs.com\r\n";$out .= "Connection: Close\r\n\r\n";fwrite($fp, $out);$content = '';while (!feof($fp))
{$content .= fgets($fp, 128);
}echo $content;fclose($fp);
}
执行这段代码后,会显示返回信息,还有这个页面的HTML代码:
HTTP/1.1 200OKDate: Sun, 26 Jan 2014 01:41:56GMT
Content-Type: text/html; charset=utf-8Content-Length: 44177Connection:close
Vary: Accept-Encoding
Cache-Control: public, max-age=104Expires: Sun, 26 Jan 2014 01:43:33GMT
Last-Modified: Sun, 26 Jan 2014 01:41:33GMT
X-AspNetMvc-Version: 3.0X-AspNet-Version: 4.0.30319X-Powered-By: ASP.NET
X-UA-Compatible: IE=10
PS: PHP fsockopen需要 PHP.ini 中 allow_url_fopen 选项开启。
//fsocket模拟post提交
$url = "http://localhost/test2.php?site=nowamagic.net";print_r(parse_url($url));//echo $query;
sock_get($url,"user=gonn");//sock_get($url, $query);
//fsocket模拟get提交
function sock_get($url, $query)
{$data = array('foo'=>'bar',
'baz'=>'boom',
'site'=>'www.nowamagic.net',
'name'=>'nowa magic');$query_str = http_build_query($data);$info = parse_url($url);$fp = fsockopen($info["host"], 80, $errno, $errstr, 3);//$head = "GET ".$info['path']."?".$info["query"]." HTTP/1.0\r\n";
$head = "GET ".$info['path']."?".$query_str." HTTP/1.0\r\n";$head .= "Host: ".$info['host']."\r\n";$head .= "\r\n";$write = fputs($fp, $head);while (!feof($fp))
{$line = fread($fp,4096);echo $line;
}
}
sock_post($url,"user=gonn");function sock_post($url, $query)
{$info = parse_url($url);$fp = fsockopen($info["host"], 80, $errno, $errstr, 3);$head = "POST ".$info['path']."?".$info["query"]." HTTP/1.0\r\n";$head .= "Host: ".$info['host']."\r\n";$head .= "Referer: http://".$info['host'].$info['path']."\r\n";$head .= "Content-type: application/x-www-form-urlencoded\r\n";$head .= "Content-Length: ".strlen(trim($query))."\r\n";$head .= "\r\n";$head .= trim($query);$write = fputs($fp, $head);while (!feof($fp))
{$line = fread($fp,4096);echo $line;
}
}
接收页面 test2.php 的代码为:
$data = $_REQUEST;echo '
';print_r( $data);echo '';