php通过CURL模拟post提交请求

<pre class="brush:php;toolbar:false">  /** *模拟post进行url请求 *@paramstring$url *@paramstring$param */ functionrequest_post($url=&#39;&#39;,$param=&#39;&#39;){ if(empty($url)||empty($param)){ returnfalse; } $postUrl=$url; $curlPost=$param; $ch=curl_init();//初始化curl curl_setopt($ch,CURLOPT_URL,$postUrl);//抓取指定网页 curl_setopt($ch,CURLOPT_HEADER,0);//设置header curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//要求结果为字符串且输出到屏幕上 curl_setopt($ch,CURLOPT_POST,1);//post提交方式 curl_setopt($ch,CURLOPT_POSTFIELDS,$curlPost); $data=curl_exec($ch);//运行curl curl_close($ch); return$data; }</pre><p>下面是具体的调用案例。</p><pre class="brush:php;toolbar:false"> functiontestAction(){ $url=&#39;http://mobile.jschina.com.cn/jschina/register.php&#39;; $post_data[&#39;appid&#39;]=&#39;10&#39;; $post_data[&#39;appkey&#39;]=&#39;cmbohpffXVR03nIpkkQXaAA1Vf5nO4nQ&#39;; $post_data[&#39;member_name&#39;]=&#39;zsjs123&#39;; $post_data[&#39;password&#39;]=&#39;123456&#39;; $post_data[&#39;email&#39;]=&#39;zsjs123@126.com&#39;; $o=&quot;&quot;; foreach($post_dataas$k=&gt;$v) { $o.=&quot;$k=&quot;.urlencode($v).&quot;&amp;&quot;; } $post_data=substr($o,0,-1); $res=$this-&gt;request_post($url,$post_data); print_r($res); }</pre><p>这样就提交请求,并且获取请求结果了。</p><p>一般返回的结果是json格式的。</p><p></p><p>第二种方式:</p><pre class="brush:php;toolbar:false">  /** *模拟post进行url请求 *@paramstring$url *@paramarray$post_data */ functionrequest_post($url=&#39;&#39;,$post_data=array()){ if(empty($url)||empty($post_data)){ returnfalse; } $o=&quot;&quot;; foreach($post_dataas$k=&gt;$v) { $o.=&quot;$k=&quot;.urlencode($v).&quot;&amp;&quot;; } $post_data=substr($o,0,-1); $postUrl=$url; $curlPost=$post_data; $ch=curl_init();//初始化curl curl_setopt($ch,CURLOPT_URL,$postUrl);//抓取指定网页 curl_setopt($ch,CURLOPT_HEADER,0);//设置header curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//要求结果为字符串且输出到屏幕上 curl_setopt($ch,CURLOPT_POST,1);//post提交方式 curl_setopt($ch,CURLOPT_POSTFIELDS,$curlPost); $data=curl_exec($ch);//运行curl curl_close($ch); return$data; }</pre><p>将拼接也封装了起来,这样调用的时候就更简洁了。</p><pre class="brush:php;toolbar:false">functiontestAction(){ $url=&#39;http://mobile.jschina.com.cn/jschina/register.php&#39;; $post_data[&#39;appid&#39;]=&#39;10&#39;; $post_data[&#39;appkey&#39;]=&#39;cmbohpffXVR03nIpkkQXaAA1Vf5nO4nQ&#39;; $post_data[&#39;member_name&#39;]=&#39;zsjs124&#39;; $post_data[&#39;password&#39;]=&#39;123456&#39;; $post_data[&#39;email&#39;]=&#39;zsjs124@126.com&#39;; //$post_data=array(); $res=$this-&gt;request_post($url,$post_data); print_r($res); }</pre>
RangeTime:0.006726s
RangeMem:206.55 KB
返回顶部 留言