The example in this article describes how PHP uses the socket to send HTTP requests. Share to everyone for your reference, as follows:
Socket mode:
$socket = Socket_create (Af_inet, Sock_stream, sol_tcp);//socket_set_option ($socket, Sol_socket, So_sndtimeo, Array (" SEC "=>20," USEC "=>0)); Socket_connect ($socket, ' www.baidu.com ', 80);//The inside of the newline represents \ r \ n Note that there may be spaces behind the copy code $http = < <
Fsockopen Way:
$fp = Fsockopen ("www.baidu.com", $errno, $errstr, +), if (! $fp) { echo "$errstr ($errno)
\ n ";} else { $out = "get/http/1.1\r\n"; $out. = "host:www.baidu.com\r\n"; $out. = "connection:close\r\n\r\n"; Fwrite ($fp, $http); while (!feof ($fp)) { echo fgets ($fp, +); } Fclose ($FP);}
Original socket Mode:
$fp = Stream_socket_client ("tcp://www.baidu.com:80", $errno, $errstr, +), if (! $fp) {echo "$errstr ($errno)
\ n ";} else {$http = <<
Stream mode (GET):
$http = <<
Array (' header ' = = $http, ' timeout ' =>1,//Timeout seconds ' method ' = ' GET ',//Default way ' Protocol_v Ersion ' + ' 1.1 ',//default is 1.0),///parameter format reference Http://php.net/manual/zh/context.http.php//curl format can be referenced; http://php.net/ Manual/zh/context.curl.php$context = Stream_context_create ($hdrs); Echo file_get_contents (' http://www.baidu.com ', 0 , $context);
Stream Mode post:
$postdata = http_build_query (Array (' act ' = ' save ', ' ID ' =>387171)); $http = <<
Array (' header ' = = $http, ' timeout ' =>1,//Timeout seconds ' method ' = ' POST ', ' content ' = $p Ostdata, ' protocol_version ' = ' 1.1 ',//default = 1.0);//Parameter Format reference Http://php.net/manual/zh/context.http.php//curl The format of the method can be referenced; http://php.net/manual/zh/context.curl.php$context = Stream_context_create ($hdrs); Echo file_get_contents (' http://test.cm/song.php ', 0, $context);
Note: The Host header must be included in the http1.1, while the http1.0 can have no
More about PHP related content readers can view the topic: "PHP Socket Usage Summary", "PHP Basic Grammar Primer Tutorial", "PHP error and Exception handling method summary" and "PHP common functions and Skills summary"
I hope this article is helpful to you in PHP programming.
The above describes how PHP uses the socket to send HTTP requests, including the aspects of the content, I hope the PHP tutorial interested in a friend helpful.