模拟post请求(PHP)

 1 <?php
 2     
 3     //=========================模拟post请求====================================
 4    // ===========================================================
 5     /**
 6      * 模拟post进行url请求
 7      * @param string $url
 8      * @param array $post_data
 9      */
10     function request_post($url = '', $post_data = array()) {
11         if (empty($url) || empty($post_data)) {
12             return false;
13         }
14         
15         $o = "";
16         foreach ( $post_data as $k => $v ) 
17         { 
18             $o.= "$k=" . urlencode( $v ). "&" ;
19         }
20         $post_data = substr($o,0,-1);
21 
22         $postUrl = $url;
23         $curlPost = $post_data;
24         $ch = curl_init();//初始化curl
25         curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
26         curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
27         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
28         curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
29         curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
30         $data = curl_exec($ch);//运行curl
31         curl_close($ch);
32         
33         return $data;
34     }
35     
36     public function actionPost(){
37         $url = 'http://XXXXXXXXX';
38         $post_data['username']       = '2015ceshi';
39         $post_data['password']      = '123456';
40         
41         //$post_data = array();
42         $res = $this->request_post($url, $post_data);       
43         print_r($res);
44 
45     }

 

posted @ 2015-04-09 19:51  it80  阅读(261)  评论(0编辑  收藏  举报