Home  >  Article  >  Backend Development  >  PHP实现模仿socket请求返回页面的方法_PHP

PHP实现模仿socket请求返回页面的方法_PHP

WBOY
WBOYOriginal
2016-05-31 19:28:31823browse

本文实例讲述了PHP实现模仿socket请求返回页面的方法。分享给大家供大家参考。具体实现方法如下:

代码如下:

 $url = "www.XXXX.com";  //自己做替换
 $parse = parse_url($url);  //对URL进行解析,返回起组成部分。
 $host = $parse['host'];
 $path = $parse['path'];
 $port = 80;
 $timeout = 80;
 $fp = @fsockopen($host, $port, $errno, $errstr, $timeout);  //打开socket链接
 if (!$fp){
     echo $errno."--".$errstr;  //如果错误,则返回错误代码和错误信息
 } else {
     $out = "POST $path HTTP/1.1\r\n";  //以下是HTTP请求头信息
     $out .= "Host: ".$host."\r\n";
     $out .= "Accept: */*\r\n";
     $out .= "Connection: Close\r\n";
     $out .= "Cookie: $cookie\r\n\r\n";
   
     @fwrite($fp, $out);  //把请求信息写到链接中
     $status = stream_get_meta_data($fp);
     if(!$status['timed_out']) {    
                 while (!feof($fp)) { 
                     if(($header = @fgets($fp)) && ($header == "\r\n" ||  $header == "\n")) {    
                         break;    
                     }    
                 }    
        
                 $stop = false;    
                 while(!feof($fp) && !$stop) {    
                     $data = fread($fp,8192);      //8192为可返回字节数
                     $return .= $data;        
                 }    
             }    
     fclose($fp);
     print_r($return);
 }

希望本文所述对大家的PHP程序设计有所帮助。

Statement:
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