柳暗花明笔记

    php 模拟 HTTP的POST 请求

    所属分类:[ php&web ] 猫哲学家 发表于:2012-10-16 10:29 浏览:539

    <?php /**  * HTTP Request Class  * @author Chelin Tsien  * @since 2010-11-15  * @param :  * $option = array(  *     'ssl_enable'      => true,  *     'ssl_verifypeer'  => false,  //依赖于ssl_enable  *     'http_header'     => array(  // OR FALSE  *     'User-Agent: Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)',  *     "Referer: http://XXXXXX/index.php?controller=game&action=index&id=$game",  * ),  * 'cookie_enable'   => true,  * 'cookiefile'      => true,  //依赖于cookie_enable  * 'cookiejar'       => true,  //依赖于cookie_enable  * 'referer'         => "http://".$host,  * 'header'          => true,  * 'returntransfer'  => true,  *     'cookie_save_file'=> false,  * );  */ class fSocket{ public $method = "POST"; public $port = 80; public $cookie_save_file;  /**  * Use Curl    */ protected  function _curl ($host, $path, $data, $option){         $url = $host.$path;          //echo $url ;exit;         $ch  = curl_init();     curl_setopt($ch, CURLOPT_URL, $url);          if($this->is_enable($option, 'ssl_enable')) {          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->is_enable($option,'ssl_verifypeer'));          }                  //TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly curl_setopt($ch, CURLOPT_RETURNTRANSFER, !isset($option['returntransfer']) ? TRUE : $option['returntransfer']); curl_setopt($ch, CURLOPT_HEADER, $this->is_enable($option,'header'));          if (!empty($option['http_header'])&& is_array($option['http_header'])) { curl_setopt($ch, CURLOPT_HTTPHEADER, $option['http_header']); }                  if($this->is_enable($option,'cookie_enable')) {          if (!$this->cookie_save_file) {          if (!empty($option['cookie_save_file'])) {             $this->cookie_save_file =  $option['cookie_save_file'];          } else {          $this->cookie_save_file =  tempnam('./tmp/','~');          }          }                   //The name of the file containing the cookie data.                 //The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file.                        $this->is_enable($option,'cookiefile') && curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookie_save_file);            //The name of a file to save all internal cookies to when the handle is closed, e.g. after a call to curl_close         $this->is_enable($option,'cookiejar') && curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookie_save_file);          }                  if ($this->method == 'POST') {          curl_setopt($ch, CURLOPT_POST, TRUE);         curl_setopt($ch, CURLOPT_POSTFIELDS, $data);;         }                  $this->is_enable($option,'referer') && curl_setopt($ch, CURLOPT_REFERER, $option['referer']); $result = curl_exec($ch); if(curl_errno($ch)) {     echo 'Curl error: ' . curl_error($ch); } //Close a cURL session curl_close($ch); return $result; } /**  * Open Internet or Unix domain socket connection  */ protected function _fsockopen($host, $path, $data, $option) { $port = isset($option['port']) && is_numeric($option['port']) ? $option['port'] : $this->port; $fp = fsockopen($host, $port, $errorNumber, $errorString);                  if(!$fp) {             return FALSE;         } //push param $send_params = $this->method . " " . $path ." HTTP/1.1/r/n";         $send_params .= "Host: $host/r/n";         if  (!empty($option['http_header'])&& is_array($option['http_header'])){     $send_params .= implode("/r/n", $option['http_header']) . "/r/n";         }         $send_params .= "Content-Type: application/x-www-form-urlencoded/r/n";                  if ($this->method == "POST") {             $send_params.= "Content-Length: ".strlen($data)."/r/n";         }         $send_params.= "Connection: close/r/n/r/n";                  if ($this->method == "POST") {             $send_params .= $data;         } fwrite($fp, $send_params); $response = ''; while (!feof($fp)) {             $response.= fgets($fp, 128);         } $response = preg_split("//r/n/r/n/",$response);         $header = $response[0];         $responsecontent = $response[1]; if(!(strpos($header,"Transfer-Encoding: chunked") === FALSE)){             $aux = preg_split("//r/n/",$responsecontent);             $count = count($aux);             for($i=0;$i < $count;$i++) {                 if($i==0 || ($i%2==0)) {                     $aux[$i] = "";                 }             }             $responsecontent = implode("",$aux);          }//if          fclose($fp);          return rtrim($responsecontent);     } /**  * send a request  */ public function send($host, $path, $data = '', $option = array(), $method = "POST"  ){     if(in_array($method, array('GET', 'POST'), TRUE)) {      $this->method = $method; }     if((!function_exists("curl_init") && is_array($data)) || ($method == "GET" && is_array($data))) {     $url = '';     foreach ($data as $key => $val) { $url .= $key . '=' . $val . '&'; } $data = $url;         }               if ($method == "GET" && $data) {         if (strpos($path, '?') === FALSE) { $path .= '?' . $data;     } else { $path .= '&' . $data; }     }              //优先调用Curl组件,从效率上来说会好点         if(function_exists("curl_init")) {     $return_info =  $this->_curl($host, $path, $data, $option);  //CURL组件       }else {        $return_info =  $this->_fsockopen($host, $path, $data, $option); //fsockopen connection     }        return $return_info; }     public function is_enable($param, $key) { return !empty($param[$key]) ? $param[$key] : FALSE; } } Example : $f = new fSocket; $http_header =array( 'User-Agent: Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)', 'Referer: http://{$host}/index.php?controller=game&action=index&id=$game', ); $option = array(     'ssl_enable'      => true,     'ssl_verifypeer'  => false,  //依赖于ssl_enable     'http_header'     => false, 'cookie_enable'   => true, 'cookiefile'      => true,  //依赖于cookie_enable 'cookiejar'       => true,  //依赖于cookie_enable 'referer'         => "http://".$host, 'header'          => true, 'returntransfer'  => true,     'cookie_save_file'=> false, ); $response = $f->send("https://xxxx.xx.xxx", "/xx/xx.aspx?siteflag=11", $data, $option); 
    标签: http 
    上一编文章 javascript 保持滚动条在底部代码 下一编文章 记住这53个要点提高PHP编程效率
    最近文章
    发表评论