Home > Backend Development > PHP Tutorial > php模拟post请求方法总结

php模拟post请求方法总结

WBOY
Release: 2016-06-20 13:04:01
Original
1217 people have browsed it

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

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

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

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

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

<p>$purl="http://www.scutephp.com/post.php";</p>echo "以下是POST方式的响应内容:<br>"; <br /><p>sock_post($purl,"name=php程序员教程网&url=http://www.scutephp.com/");</p>
Copy after login

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

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


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template