php中socket实现GET与POST异步提交数据

作者:袖梨 2022-06-24

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

好了都好了下面就开始吧

 代码如下 复制代码

//POST提交
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");

工作需要封装好方法方便同事调用。

相关文章

精彩推荐