--------------------------------------------------------------------------------
做项目中有时需要这样一个过程,程序去数据库中读取出来数据,需要用POST方式把数据给另一个URL地址.那个URL地址以接收POST方式接收,如果在HTML里我们用,form 表单提交很容易做到.但要是让程序自已来做呢?ASP中有这样的http.open对象.PHP里拟呼不太容易做到.找了几个函数.用.fputs来实现的
--------------------------------------------------------------------------------
一个函数方法:
代码:
function posttohost($url, $data) {
$url = parse_url($url);
if (!$url) return "couldn't parse url";
if (!isset($url['port'])) { $url['port'] = ""; }
if (!isset($url['query'])) { $url['query'] = ""; }
$encoded = "";
while (list($k,$v) = each($data)) {
$encoded .= ($encoded ? "&" : "");
$encoded .= rawurlencode($k)."=".rawurlencode($v);
}
$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($encoded) . "\n");
fputs($fp, "Connection: close\n\n");
fputs($fp, "$encoded\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;
}
方法二:(没测试过)
代码:
$URL="www.mysite.com/test.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://$URL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "Data1=blah&Data2=blah");
curl_exec ($ch);
curl_close ($ch);
下需这是我用ASP实现的代码.也帖出来吧.
phone,item是变量名,
phonelist,items 是变量内容
代码:
stra = "phone="&phonelist&"&item="&items&""
Set Http = CreateObject("Microsoft.XMLHTTP")
Http.Open "POST", url, False
Http.setrequestheader "content-type","application/x-www-form-urlencoded"
Http.Send stra'发送到服务器
评论
看看这个实现的主要内容(登陆 163.com 邮箱),用 JS自动提交表单 实现转发:
test.htm:
<form method=post action="" target="_blank">http://localhost/login.php">
账号:
<input type="text" name=user>
密码:
<input type="password" name=password>
邮箱:
<select name="select">
<option>@163.com</option>
</select>
<input type="submit" name="Submit" value="提交">
</form>
login.php:
<form name=tmpF method=post name=login163 action="http://reg.163.com/in.jsp?url=http://mscan2.163.com/Unicom.jsp?verifycookie%3D1%26language%3D-1%26style%3D-1" onsubmit=doit_163()>
<?php
print ' <input type=hidden type="password" name=username value='.$HTTP_POST_VARS["user"].'>';
print ' <input type=hidden type="password" name=password value='.$HTTP_POST_VARS["password"].'>';
?>
</form>
<script language='JavaScript'>
document.tmpF.submit();
</script>
来源:http://cnknife.net/show.php?id=7
你可以使用这个链接引用该篇文章 http://publishblog.blogchina.com/blog/tb.b?diaryID=197001