Use cURL in PHP to implement Get and Post requests. For more information, see section 1. cURL.
CURL is a tool that uses URL syntax to transmit files and data. it supports many protocols, such as HTTP, FTP, and TELNET. The best thing is that PHP also supports the cURL Library. This article describes some advanced features of cURL and how to use it in PHP.
2. Basic structure
Before learning more complex functions, let's take a look at the basic steps for creating cURL requests in PHP:
(1) Initialization
Curl_init ()
(2) set variables
Curl_setopt (). This is the most important thing. There is a long string of cURL parameters that can be set. they can specify the details of URL requests. It may be difficult to read and understand all at once, so today we will only try out the more common and useful options.
(3) execute and obtain results
Curl_exec ()
(4) release the cURL handle
Curl_close ()
3. cURL implements Get and Post
3.1 Get implementation
// Initialize $ ch = curl_init (); // Set options, including URL curl_setopt ($ ch, CURLOPT_URL, "http://www.baidu.com"); curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt ($ ch, CURLOPT_HEADER, 0); // execute and obtain the HTML document content $ output = curl_exec ($ ch); // release the 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); // The post variable 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 preceding method is in json format and is interpreted as an array using the json_decode function.
$ Output_array = json_decode ($ output, true );
If json_decode ($ output) is used for parsing, data of the object type will be obtained.
For more articles about how to use cURL in PHP to implement Get and Post requests, refer to PHP Chinese website!