在使用php socket时我们需要先开启socket扩展了,我们可以使用phpinfo();查看是否开启了socket扩展,否则在php.ini中开启了,如果没有开启我们可以参考下面方法来设置.
windows 系统中socket扩展
windows 下可以直接修改php.ini 文件 去掉extension=php_sockets.dll 前面的分号重启就OK了
在linux下给PHP安装socket扩展,代码如下:
- #cd /home/php5.2.1/ext/sockets
- #/server/php/bin/phpize
- #./configure --prefix=/usr/local/php/lib --with-php-config=/server/php/bin/php-config --enable-sockets
- #make
- #make install
- 再修改/usr/local/php/etc/php.ini文件
- #extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/" (php5.4版本以上不用加扩展路径)
- extension=sockets.so
重启apache,好了都好了下面就开始吧,代码如下:
-
- function socketPost($url,$data){
- $postStr = '';
- $postLen = '';
- $out = '';
-
- $urlInfo = parse_url($url);
- $host = $urlInfo['host'];
- if(!isset($urlInfo['query'])) $urlInfo['query'] ='';
- $path = $urlInfo['path'].'?'.$urlInfo['query'];
-
- foreach($data as $key=>$value){
- $postStr .=$key.'='.rawurlencode($value).'&';#这里需要对post的值进行编码,否则会出现中断
- }
- $postStr = trim($postStr,"&");
-
- $postLen = strlen($postStr);
- $fp = fsockopen($host, 80, $errno, $errstr, 3);
- if ($fp) {
-
- $out .="POST ".$path." HTTP/1.0\r\n";
- $out .="Host: ".$host."\r\n";
- $out .= "Content-type: application/x-www-form-urlencoded\r\n";
- $out .= "Content-Length: ".$postLen."\r\n"; #这里最好加上Connection: close
- $out .= "\r\n";
- $out .= $postStr;
- fwrite($fp, $out);
- fclose($fp);
- }
- }
使用方法,代码如下:
- socketPost("提交的地址",array("username"=>"这里是post的username","password"=>321312312));
- function socketGet($url){
- $urlInfo = parse_url($url);
- $host = $urlInfo['host'];
- if(!isset($urlInfo['query'])) $urlInfo['query'] ='';
- $path = $urlInfo['path'].'?'.$urlInfo['query'];
- $fp = fsockopen($host, 80, $errno, $errstr, 3);
- if ($fp) {
-
- $out = "GET {$path} / HTTP/1.1\r\n";
- $out .= "Host: {$host}\r\n";
- $out .= "Connection: Close\r\n\r\n";
- fwrite($fp, $out);
- fclose($fp);
- }
- }
使用方法:socketGet("url");工作需要封装好方法方便同事调用. |