/** * using php socket programming to simulate http post and get requests * @author koma */class Http{private $sp = "\ r \ n"; //here must be written in double quotes private $protocol = ' http/1.1 ' ;p rivate $requestLine = "";p rivate $requestHeader = ";p rivate $requestBody = "";p rivate $requestInfo = "";p rivate $fp = null;private $ urlinfo = null;private $header = array ();p rivate $body = array (); Public function __construct ($url) {$this->parseurl ($url), $port = isset ($this, urlinfo[' Port ']) ? isset ($this->urlinfo[' port ') : ';/* * ' Note: The URL parameter in Fsockopen here is "www.xxx.com" * not able to take "http://" */$this->fp = fsockopen ($ this->urlinfo[' host '], $port, $errno, $errstr, 30);if ( ! $this->fp ) {echo $errstr. ' ('. $errno. ') '; ExIt ();} $this->header[' host '] = $this->urlinfo[' host ';} Public function get ($header = array (), $body = array ()) {$this Header = array_merge ($this->header, $header) $this->body = $body $this Request (' GET ');} Public function post ($header = array (), $body = array ()) {$this Header = array_merge ($this->header, $header) $this->body = $body $this Request (' POST ');} Private function request ($method) {$header = ""; $this->requestline = $ Method. ' '. $this->urlinfo[' path ']. ' '. $this->protocol;foreach ( $this->header as $key => $value ) {$header .= $header == " ? $key. ': '. $value : $this->sp. $key . ': '. $value;} $this->requestheader = $header. $this->sp $this->sp; $this->requestinfo = $this->requestline. $this->sp. $this->requestheader;if ( !empty ($this Body) {$body = ;foreach ( $this->body as $key => $ value ) {$body .= $body == " ? $key. ' = '. $value : ' & ' $key. ' = '. $value;} $this->requestinfo .= $body;} if ( fwrite ($this->fp, $this->requestinfo) ) {while ( !feof ($this- >FP) ) {$str = fread ($this->fp, 1024);echo $str;} Fclose ($this->fp);} Private function parseurl ($url) {$this->urlinfo = parse_url ($url);} $url = "http://news.163.com/14/1102/01/AA0PFA7Q00014AED.html"; $http = new http ($url) ;/* send GET request */echo $http->get (Array (' user-agent ' => ' mozilla/5.0 (Windows  NT 6.1; WOW64) AppleWebKit/537.36 (khtml, like geCKO) chrome/35.0.1916.153 safari/537.36 ',);/* send a POST request echo $http->post (' User-agent ' => ' mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (Khtml, like gecko) chrome/35.0.1916.153 safari/537.36 ',//must add these two for post requests ' Content-length ' => 20, ' content-type ' => ' application/x-www-form-urlencoded '), Array (' username ' = ' koma ', ' age ' =>22); * *
Take a look, what do you think? Please correct me!
Php+socket analog send GET, POST request