php socket模拟http中post或get提交数据

php socket模拟http中post或者get提交数据的示例代码。

代码:
sock_post.php:

<?php
/**
* php socket模拟post\get请求
* 编辑:脚本学堂 http://www.jbxue.com
*/
function sock_post($url, $data='') {
$url = parse_url($url);
$url['scheme'] || $url['scheme'] = 'http';
$url['host'] || $url['host'] = $_SERVER['HTTP_HOST'];
$url['path'][0] != '/' && $url['path'] = '/'.$url['path'];

$query = $data;
if(is_array($data)) $query = http_build_query($data);

$fp = @fsockopen($url['host'], $url['port'] ? $url['port'] : 80);
if (!$fp) return "Failed to open socket to $url[host]";

fputs($fp, sprintf("POST %s%s%s HTTP/1.0/n", $url['path'], $url['query'] ? "?" : "", $url['query']));
fputs($fp, "Host: $url[host]/n");
fputs($fp, "Content-type: application/x-www-form-urlencoded/n");
fputs($fp, "Content-length: " . strlen($query) . "/n");
fputs($fp, "Connection: close/n/n");

fputs($fp, "$query/n");

$line = fgets($fp,1024);

if (@!eregi("^HTTP/1/.. 200", $line)) return;

$results = "";
$inheader = 1;
while(!feof($fp)) {
$line = fgets($fp,1024);
if ($inheader && ($line == "/n" || $line == "/r/n")) {
$inheader = 0;
}elseif (!$inheader) {
$results .= $line;
}
}
fclose($fp);

return $results;
}
$re = sock_post('http://localhost/direct_post/get_post.php?id=1',array('wel'=>'hello'));
echo $re;
?>


get_post.php:
<?php
echo "post:";
print_r($_POST);
echo 'get:';
print_r($_GET);
?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值