PHP USES cURL to implement the Get and Post request methods
- 2020-05-30 19:43:58
- OfStack
1. cURL is introduced
cURL is a tool for transferring files and data using the URL syntax. It supports many protocols, such as HTTP, FTP, TELNET, and so on. Best of all, PHP also supports the cURL library. This article describes some of the advanced features of cURL and how to use it in PHP.
2. Basic structure
Before getting into more complex features, let's take a look at 1 of the basic steps for creating an cURL request in PHP:
(1) initialization
curl_init ()
(2) set variables
curl_setopt (). Most important of all, here lies the mystery. There is a long list of cURL parameters to set, which specify the details of the URL request. It can be difficult to read and understand all at once, so today we'll just try the more commonly used and useful options.
(3) execute and obtain the results
curl_exec ()
(4) release the cURL handle
curl_close ()
3.cURL implements Get and Post
3.1 Get implementation
// Initialize the
$ch = curl_init();
// Set options, including URL
curl_setopt($ch, CURLOPT_URL, "https://www.ofstack.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
// Execute and get HTML The document content
$output = curl_exec($ch);
// The release of curl handle
curl_close($ch);
// Print the obtained data
print_r($output);
3.2 Post implementation
$url = "http://localhost/web_services.php";
$post_data = array ("username" => "bob","key" => "12345");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// post data
curl_setopt($ch, CURLOPT_POST, 1);
// post The variables of
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
// Print the obtained data
print_r($output);
The data obtained in the above method is in json format, which is interpreted as an array using the json_decode function.
$output_array = json_decode ($output true);
If you parse with json_decode($output), you get data of type object.