php模拟post请求方法总结

原创
2016-06-20 13:04:01 894浏览

php 模拟 post 请求方法主要有两种办法,通过 fsocket 和通过 curl。

下面就简单的举两个案例说明一下 php 如何使用这两种方法模拟 post 请求。

(1)php 通过 fsocket 模拟 post 提交请求

function sock_post($url,$query){
$info=parse_url($url);
$fp=fsockopen($info["host"],80,$errno,$errstr,3);
$head="POST ".$info['path']." HTTP/1.0\r\n";
$head.="Host: ".$info['host']."\r\n";
$head.="Referer: http://".$info['host'].$info['path']."\r\n";
$head.="Content-type: application/x-www-form-urlencoded\r\n";
$head.="Content-Length: ".strlen(trim($query))."\r\n";
$head.="\r\n";
$head.=trim($query);
$write=fputs($fp,$head);
while(!feof($fp)){
$line=fgets($fp);
echo $line."
";
}

}

使用方法如下(注意$url这个参数必须是域名,不可以是localhost这种形式的url):

$purl="http://www.scutephp.com/post.php";

echo "以下是POST方式的响应内容:
";

sock_post($purl,"name=php程序员教程网&url=http://www.scutephp.com/");

(2)php 通过 curl 模拟 post 提交请求

$url='http://www.scutephp.com/post.php';
$fields=array(
'lname'=>'justcoding',
'fname'=>'phplover',
'title'=>'myapi',
'email'=>'1290026290@qq.com',
'phone'=>'188888888888'
);
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields);
ob_start();
curl_exec($ch);
$result=ob_get_contents();
ob_end_clean();
echo $result;
curl_close($ch);


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。