This article mainly introduces how PHP uses socket to send HTTP requests, and analyzes common skills of PHP in sending http requests using socket in the form of examples, for more information about how PHP uses socket to send HTTP requests, see the following example. We will share this with you for your reference. The details are 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 line feed indicates \ r \ n. Note that there may be spaces behind the copied code $ http = <
Fsockopen mode:
$fp = fsockopen("www.baidu.com", 80, $errno, $errstr, 30);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, 128); } fclose($fp);}
Original socket method:
$ Fp = stream_socket_client ("tcp: // www.baidu.com: 80", $ errno, $ errstr, 30); if (! $ Fp) {echo "$ errstr ($ errno)
\ N ";}else {$ http = <
Stream method (get ):
$ Http = <
Array ('header' => $ http, 'timeout' => 1, // timeout second 'method' => 'get ', // the default method is 'protocol _ version' => '1. 1', // The default value is 1.0),); // for the parameter format, refer to parameter layout = stream_context_create ($ hdrs); echo file_get_contents ('http: // www.baidu.com ', 0, $ context );
Stream post:
$ Postdata = http_build_query (array ('Act '=> 'Save', 'id' => 387171); $ http = <
Array ('header' => $ http, 'timeout' => 1, // timeout second 'method' => 'post', 'content' => $ postdata, 'protocol _ version' => '1. 1', // The default value is 1.0),); // for the parameter format, see paihttp://php.net/manual/zh/context.curl.php?context = stream_context_create ($ hdrs); echo file_get_contents ('http: // test. cm/song. php ', 0, $ context );
Note: http1.1 must contain the Host header, but http1.0 may not