首页 > 代码库 > PHP模拟POST提交数据三种方式
PHP模拟POST提交数据三种方式
PHP模拟POST提交数据有file_get_contents、curl和socket,他们都可以通过模拟POST提交,实现POST数据传输。
file_get_contents模拟POST提交:
$arr=array(‘http’=>array(‘method’=>’POST’,’content’=>’name=wang&pwd=123′));
$result = file_get_contents(“www.wangzhiguang.com.cn”,false,stream_context_create($arr))
http://dict.baidu.com/s?wd=%E6%B4%9B%E4%B8%BD%E8%AF%97+%E4%BD%A0%E7%9A%84%E9%80%89%E6%8B%A9+%E6%89%BE%E5%9B%9E%E8%87%AA%E4%BF%A1%E4%B8%8E%E9%AA%84%E5%82%B2
curl模拟POST提交:
$arr = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => array(‘name’=>’wang’,’pwd’=>’123′)
);
$ch = curl_init($url);
curl_setopt_array($ch, $arr);
$result = curl_exec($ch);
curl_close($ch);
socket来模拟POST提交:
$url = “www.wangzhiguang.com.cn”;
$host = 80;
$content = ‘name=wang&pwd=123′;
$fp = fsockopen($content, $host, $errno, $errstr);
$length = strlen($content);
$header = <<<HEADER
POST {$url} HTTP/1.1
Host: {$host}
Content-Type: application/x-www-form-urlencoded
Content-Length: {$length}
Connection: close
{$content}
HEADER;
fwrite($fp, $header);
while (!feof($fp)) {
$result .= fread($fp, 512);
}
http://dict.baidu.com/s?wd=%E3%80%90%E5%88%98%E5%BF%83%E8%AF%AD%E6%B8%85%E6%9C%9D%E5%AE%AB%E5%BB%B7%E4%B8%B0%E8%83%B8%E8%8C%B6+100%25%E4%B8%B0%E8%83%B8%E6%88%90%E5%8A%9F+%E4%B8%80%E4%B8%AA%E6%9C%88%E5%A2%9E%E5%8A%A0%E4%B8%80%E4%B8%AA%E7%BD%A9%E6%9D%AF%E3%80%91
$result = explode(“\r\n\r\n”, $result, 2);
connection: close和post数据之间要空一行
最好通过返回值$result你就可以看到发送状态了。
PHP模拟POST提交数据三种方式