php post到指定URL——fsockopen


<?php
function sendpost($url, $data){
//先解析url
$url = parse_url($url);
$url_port = !isset($url['port']) ? (($url['scheme'] == 'http') ? 80 : 443) : $url['port'];
if (!$url)
{
return "couldn't parse url";
}
//将参数拼成URL key1=value1&key2=value2 的形式
$encoded = "";
while (list($k, $v) = each($data))
{
$encoded .= ($encoded ? '&' : '');
$encoded .= rawurlencode($k)."=".rawurlencode($v);
}
$len = strlen($encoded);
//拼上http头
$out = "POST ".$url['path'].(isset($url['query']) ? ('?'.$url['query']) : '')." HTTP/1.1\r\n";
$out .= "Host:".$url['host']."\r\n";
$out .= "Content-type: application/x-www-form-urlencoded\r\n";
$out .= "Connection: Close\r\n";
$out .= "Content-Length: $len\r\n";
$out .= "\r\n";
$out .= $encoded."\r\n";
//打开一个sock
$fp = @fsockopen($url['host'], $url_port);
$line = "";
if(!$fp){
echo "$errstr($errno)\n";
}else{
fwrite($fp,$out);
while (!feof($fp))
{
$line .= fgets($fp, 2048);
}
}
//去掉头文件
if ($line)
{
$body = stristr($line, "\r\n\r\n");
$body =substr($body, 4, strlen($body));
$line = $body;
}
fclose($fp);
return $line;
}
$arrVal["eee"] = "Hello";
$arrVal["ee"] = "Sorry";
echo sendpost("http://localhost/test.php",$arrVal);
?>

post.php 的内容

<?php
while(list($k,$v) = each($HTTP_POST_VARS)){
echo "<h1>".$k."=".$v."<h1><br />";
}
?>



function sendpost($url, $data,$sendType='POST'){
//先解析url
$url = parse_url($url);
$url_port = !isset($url['port']) ? (($url['scheme'] == 'http') ? 80 : 443) : $url['port'];
if (!$url)
{
return "couldn't parse url";
}
//将参数拼成URL key1=value1&key2=value2 的形式
$encoded = "";
while (list($k, $v) = each($data))
{
$encoded .= ($encoded ? '&' : '');
$encoded .= rawurlencode($k)."=".rawurlencode($v);
}
$len = strlen($encoded);
//拼上http头
$out = "{$sendType} ".$url['path'].(isset($url['query']) ? ('?'.$url['query']) : '')." HTTP/1.1\r\n";
$out .= "Host:".$url['host']."\r\n";
$out .= "Content-type: application/x-www-form-urlencoded\r\n";
$out .= "Connection: Close\r\n";
$out .= "Content-Length: $len\r\n";
$out .= "\r\n";
$out .= $encoded."\r\n";
//打开一个sock
$fp = @fsockopen($url['host'], $url_port);
$line = "";
if(!$fp){
echo "$errstr($errno)\n";
}else{
fwrite($fp,$out);
while (!feof($fp))
{
$line .= fgets($fp, 2048);
}
}
//去掉头文件
if ($line)
{
$body = stristr($line, "\r\n\r\n");
$body =substr($body, 4, strlen($body));
$line = $body;
}
fclose($fp);
return $line;
}



此文章来自网上,仅供参考
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值