文件:phpinput_post.php 发送post数据(流数据),利用socket发送
<?php
/**
* 客服端发送post流数据的请求
*/
//对数据进行封包
function parkByArr($arr){
$atArr = array();
foreach ($arr as $k => $v){
$atArr[]=pack($v[0], $v[1]);
}
return $atArr;
}
//c/c++也可以按照这种格式打包数据
$format = array(
"username" => array("A20","张三adfb12"),
"pass" => array("A10","asdf*#1"),
"age" => array("C","23"),
"birthday" => array("I","19900101"),
"email" => array("A50","zhangsan@163.com")
);
//各个数据之间以\0分割连成字符串
$stream = implode("\0",parkByArr($format));
$http_entity_body = $stream; //要发送的数据
$http_entity_type = 'application/x-www-from-urlencoded'; //发送的格式
$http_entity_length = strlen($http_entity_body);
$host = '127.0.0.1'; //数据发送ip
$port = '80'; //端口
$path = '/phpinput_server.php'; //发送的url,注意要带上路径啊,我这里两个文件都在根目录,所以不影响
$fp = fsockopen($host, $port, $error_no, $error_desc, 30); //开启socket
//发送post请求给url: phpinput_server.php
if($fp) {
fputs($fp, "POST {$path} HTTP/1.1\r\n");
fputs($fp, "HOST: {$host}\r\n");
fputs($fp, "Content-type: {$http_entity_type}\r\n");
fputs($fp, "Content-Length: {$http_entity_length}\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $http_entity_body."\r\n\r\n");
while(!feof($fp)) {
$d .= fgets($fp, 4096);
}
fclose($fp);
echo $d;
}
?>
文件:phpinput_server.php 接受post请求并解包,把接受到的数据写入文件test.php
<?php
/**
* 服务端接受客服端post过来的数据(流数据)
*/
//根据包的格式解包地址
function unparkByArr($post_str,$format){
$Arr = explode("\0",$post_str); //post数据是以\0分割的
$atArr = array();
$i = 0;
foreach($format as $k=>$v){
$tmp = unpack($v[0],$Arr[$i]);
$atArr[$k] = $tmp[1];
$i++;
}
return $atArr;
}
//解包的格式,和打包的格式一致
$format = array(
"username" => array("A20"),
"pass" => array("A10"),
"age" => array("C"),
"birthday" => array("I"),
"email" => array("A50")
);
//接受post请求
$post_data = file_get_contents('php://input', 'r');
//解包操作
$post_data = unparkByArr($post_data,$format);
//写入文件方便查看
file_put_contents('text.php', "<?php \n\$package=".var_export($post_data, ',')."\n?>");
?>
用这种方式可以实现c/c++和php的进行数据通讯
示例下载地址:http://tpblog.googlecode.com/files/php%E7%9A%84socket%E5%8F%91%E9%80%81post%E8%AF%B7%E6%B1%82%E7%A4%BA%E4%BE%8B.zip