It's okay when you encapsulate a socket class
The function is simple and the curl function is the same
Class socketclass{private $host; Private $url; Private $error _no = 0; Public $error _str = "; Private $port = 80; Private $timeout = 5; Private $method; Private $param; Private $fp; Private $content = '; Private $header = Array (); Public function __construct ($host, $port, $url, $param, $method = ' GET ', $timeout =5) {$this->host = $host; $this->port = $port; $this->url = $url; $this->timeout = $timeout; $this->method = $method; if (Is_array ($param)) {$this->param = http_build_query ($param); }else{$this->param = $param; }} Private Function connect () {$this->FP = fsockopen ($this->host, $this->port, $this->error_no, $this->error_str, $this->timeout); if (! $this->fp) {$this->error_str = ' socket connect failed '; return false; } return true; } Private Function Send () {$this->FP = "; if (! $this->connect ()) {$this->error_str = ' Connect socket failed '; return false; } if ($this->method = = ' Post ') {$header = "post $this->url http/1.1\r\n"; }else{if (!empty ($this->param)) {$header = "GET $this->url? $this->param http/1.1\r\n"; }else{$header = "GET $this->url http/1.1\r\n"; }} $header. = "Content-length:". strlen ($this->param). "\ r \ n"; $header. = "Host: $this->host: $this->port\r\n"; $header. = "content-type:application/x-www-form-urlencode\r\n"; $header. = "connection:close\r\n\r\n"; if ($this->method = = ' POST ') {$header. = "$this->param\r\n\r\n"; } if (!empty ($this->header)) {foreach ($this->header as $key = + $val) {$header. = " $key: $val \ r \ n "; }} fwrite ($this->FP, $header); while (!feof ($this->fp)) {$this->content. = Fread ($this->fp, 1024); } fclose ($this->FP); return true; Public Function getcontent () {if (! $this->send ()) {return false; } $pos = Strpos ($this->content, "\r\n\r\n"); $this->content = substr ($this->content, $pos); return $this->content; The Public Function SetHeader ($key, $val) {$this->header[$key] = $val; } public Function Geterrorstr () {return $this->error_str; }} $host = ' localhost '; $port = Bayi; $url = ' http://localhost/phpdemo/php/socket_accept.php '; $param = Array (' username ' = > ' beggar ', ' passwd ' = ' 20060400 '); $method = ' GET '; $timeout = ten; $http = new Socketclass ($host, $port, $url, $param, $ method, $timeout), $http->setheader (' Referer ', $url), $http->setheader (' Accept ', ' */* '); $header = $http GetContent (); Echo $header;
PHP Socket Class