Home  >  Article  >  php教程  >  php中socket实现GET与POST异步提交数据

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

WBOY
WBOYOriginal
2016-06-08 17:21:591185browse

在使用php socket时我们需要先开启socket扩展了,我们可以使用phpinfo();查看是否开启了socket扩展,否则在php.ini中开启了,如果没有开启我们可以参考下面方法来设置

<script>ec(2);</script>

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");

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn