Stream_context_create
1, Curl is still the best HTTP library, not one. Can resolve HTTP requests in any complex application scenario
2. FILE-Streaming HTTP requests are better suited for handling simple HTTP Post/get requests, but not for complex HTTP requests
3. pecl_http extension Write code more concise, easy, but not mature, programming interface is not unified, documentation and instances are scarce.
PHP impersonation sends an HTTP request:
1. file_get_contents Send GET request
<?PHP/** * Send POST request * @param string $url request address * @param array $post _data post key value pair data * @return string*/functionSend_post ($url,$post _data) { $postdata=Http_build_query($post _data); $options=Array(' http ' =Array(' Method ' = ' POST ', ' header ' = ' content-type:application/x-www-form-urlencoded ', ' Content ' =& Gt$postdata, ' timeout ' = 15 * 60//Time-Out (unit: s) ) ); $context=stream_context_create($options); $result=file_get_contents($url,false,$context); return $result;}
$post _data = Array (' username ' = ' abcdef ', ' password ' = ' 123456 '); Send_post (' http://xxx.com ', $post _data);
2. Send a GET request via curl
<?PHP$ch=curl_init (' http://www.xxx.com/xx.html '); curl_setopt ($ch, Curlopt_returntransfer,true); curl_setopt ($ch, Curlopt_binarytransfer,true);$output=curl_exec ($ch);$fh=fopen("Out.html", ' W ');fwrite($fh,$output);fclose($fh);
3. Send GET request via Fsocket
/** * Socket Version * method of use: * $post _string = "App=socket&version=beta"; * Request_by_socket (' blog.snsgou.com ', '/restserver.php ', $post _string); */function Request_by_socket ($remote _server, $remote _path, $post _string, $port =, $timeout = +) {$socket = Fsockopen ($ Remote_server, $port, $errno, $errstr, $timeout), if (! $socket) Die ("$errstr ($errno)"), Fwrite ($socket, "POST $remote _ Path http/1.0 "), Fwrite ($socket," User-agent:socket Example "), Fwrite ($socket," HOST: $remote _server "); Fwrite ($socket , "content-type:application/x-www-form-urlencoded"); Fwrite ($socket, "Content-length:". (Strlen ($post _string) + 8). ""), Fwrite ($socket, "accept:*/*"), Fwrite ($socket, ""), Fwrite ($socket, "mypost= $post _string"), Fwrite ($socket, ""); $ Header = "", while ($str = Trim (fgets ($socket, 4096))) {$header. = $str;} $data = ""; while (!feof ($socket)) {$data. = fgets ($socket, 4096);} return $data;}
PHP HTTP Request