欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

PHP 以 Post 方式请求网页数据

程序员文章站 2022-05-23 14:33:42
...
PHP 以 Post 方式请求网页数据
/**
   * Post 方式请求网页数据
   *
   * @param string $url     网页地址
   * @prarm string $host    主机
   * @param string $session 会话值
   * @prarm string $type    类型(POST、GET)
   * @prarm string $port    端口
   * @prarm string $data    数据
   */
  function getPageConent( $url, $host,  $data = "" ,$session = "", $type = "POST", $port = "") {
      
      if( empty($port) ) $port = 80;     
      
      /* 请求数据 */
      $post_data = $data;
     $lenght = strlen($post_data);
     
     $headers  = "{$type} {$url} HTTP/1.1\r\n";
     $headers .= "Accept: * /*\r\n";
     $headers .= "Content-Type: application/x-www-form-urlencoded\r\n";
     $headers .= "User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; GTB6; CIBA; .NET CLR 4.0.20506)\r\n";
     if($session != "" ) $headers .= "Cookie:JSESSIONID={$session}\r\n";
     $headers .= "Host: {$host}:{$port}\r\n";
     $headers .= "Content-Length: {$lenght}\r\n";
     $headers .= "Connection: Close\r\n\r\n";
     $headers .= $post_data;
 
     if( $fp = fsockopen( $host, $port, $errno, $errstr, 100) ) {
         fwrite($fp, $headers);        
           $header   = fread($fp, 1024);    
           $content  = fread($fp, 1024);    
           $content .= fread($fp, 1024);
           $content .= fread($fp, 1024);
           $content .= fread($fp, 1024);
         fclose($fp);        
     }    
     if( $data != "" ) {
         echo $headers;
         echo "";
         echo $header;
         echo "";
         echo $content;
         echo "";
         exit;
     } else {
         return $content;
     }    
  }