1.cURL Introduction
CURL is a tool that uses URL syntax to transfer files and data, and 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 learning more complex features, take a look at the basic steps to build a curl request in PHP:
(1) initialization
Curl_init ()
(2) Setting variables
curl_setopt (). The most important thing is here. There is a long list of curl parameters that can be set to specify the details of the URL request. It may be difficult to read them all at once and to understand them, so today we'll just try some of the more commonly used and more useful options.
(3) Execute and get results
Curl_exec ()
(4) Release curl handle
Curl_close ()
3.cURL implementation of Get and post
3.1 Get Mode implementation
Initialization
$ch = Curl_init ();
Setting options, including URLs
curl_setopt ($ch, Curlopt_url, "http://www.nettuts.com");
curl_setopt ($ch, Curlopt_returntransfer, 1);
curl_setopt ($ch, Curlopt_header, 0);
Execute and get HTML document content
$output = curl_exec ($ch);
Releasing the curl handle
Curl_close ($ch);
Print the obtained data
Print_r ($output);
3.2 Post Mode 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);
Variables for post
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 this way is in JSON format, using the Json_decode function to interpret the array.
$output _array = Json_decode ($output, true);
If you use Json_decode ($output) parsing, you will get data of type object.
Curl implementation sends get and POST requests (PHP)