Home > Article > Backend Development > What are the ways to initiate HTTP requests in PHP?
PHP initiates HTTP requests in the following ways: 1. Send a get request through [file_get_contents]; 2. Send a get request through [CURL]; 3. Send a get request through [fsocket].
PHP initiates HTTP request methods:
curl is still the best HTTP Library, no one. It can solve HTTP requests in any complex application scenarios;
File streaming HTTP requests are more suitable for processing simple HTTP POST/GET requests, but are not suitable for complex HTTP requests;
PECL_HTTP extension code is more concise and trouble-free, but the maturity is not good, the programming interface is not unified, and the documentation and examples are lacking.
Related learning recommendations: PHP programming from entry to proficiency
1. file_get_contents sends get request
<?php /** * 发送post请求 * @param string $url 请求地址 * @param array $post_data post键值对数据 * @return string */ function send_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' => $postdata, 'timeout' => 15 * 60 // 超时时间(单位: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 through 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 a get request through fsocket
/** * Socket版本 * 使用方法: * $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 = 80,$timeout = 30) { $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; }
The above is the detailed content of What are the ways to initiate HTTP requests in PHP?. For more information, please follow other related articles on the PHP Chinese website!