This article mainly introduces several ways to send HTTP requests from PHP, and it is interesting to know how to send HTTP requests in addition to using CURL outside of PHP.
In PHP development we used curl to encapsulate HTTP requests, what is curl?
Curl is a tool for transmitting data that supports a variety of protocols, such as using the Curl command line under Linux to send various HTTP requests. PHP's CURL is a bottom-level library that can communicate with various servers according to different protocols, one of which is the HTTP protocol.
The modern PHP development framework often uses a package called guzzlehttp, which is an HTTP client and can also be used to send various HTTP requests, so what is the implementation of this principle, and how is CURL different?
Does guzzle require CURL?
No. Guzzle can use any HTTP handler to send requests. This means is guzzle can be used with CURL, PHP's stream wrapper, sockets, and non-blocking libraries like React. You just need to configure an HTTP handler to use a different method of sending requests.
This is a Question in the guzzlehttp documentation FAQ, and it is visible that guzzlehttp does not rely on the CURL library and supports a variety of ways to send HTTP requests.
How PHP sends HTTP requests
So here's a way to clean up the HTTP request in addition to using CURL outside of PHP.
1.cURL
How to stream 2.stream
Stream_context_create effect: Create and return a text stream and apply various options for the special process of fopen (), file_get_contents () and other processes such as timeout settings, proxy servers, request methods, and header information settings.
Take a POST request as an example:
Php
<?php/** * Created by Phpstorm. * User:tanteng * DATE:2017/7/22 * time:13:48 */function post ($url, $data) { $postdata = http_build_query ( $data c5/>); $opts = Array (' http ' = = Array (' method ' = ' + ' POST ', ' header ' = ' + ' content-type:application/ X-www-form-urlencoded ', ' content ' = $postdata ) ); $context = Stream_context_create ($opts); $result = File_get_contents ($url, False, $context); return $result;}
3.socket mode
Using sockets to establish a connection, splicing HTTP messages to send data for HTTP requests.
An example of a GET method:
Php
<?PHP$FP = Fsockopen ("www.example.com", $errno, $errstr), if (! $fp) { echo "$errstr ($errno) <br/>\n" ;} else { $out = "get/http/1.1\r\n"; $out. = "host:www.example.com\r\n"; $out. = "connection:close\r\n\r\n"; Fwrite ($fp, $out); while (!feof ($fp)) { echo fgets ($fp, +); } Fclose ($FP);}? >
This article describes several different ways to send HTTP requests.