Learn how to use the CURL extension

Posted by andrewdunstall on Fri, 14 Jan 2022 18:25:22 +0100

In fact, the CURL extension was not intended to be written. After all, it is also one of the most commonly used functions. However, since you are brushing documents, share what you have learned. Don't fall into the "Curse of knowledge". Their own knowledge system is not complete. Maybe many small partners, like me, just pursue rapid business development and simply use it without in-depth understanding. Today, let's learn more about CURL.

The CURL extension of PHP is actually an extension software based on libcurl. In linux related systems, this software is basically standard, such as CentOS and Ubuntu. We don't need to install this libcurl separately. Even if there is no libcurl, it can be easily installed.

For PHP, this extension has been integrated into the PHP source installation package. We only need to add -- with curl when compiling and installing PHP.

Use CURL to request links

Let's first look at the simplest way to use CURL to request a GET address.

$ch = curl_init("https://www.baidu.com");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); // Check whether the domain name is set in the certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // Trust any certificate

$res = curl_exec($ch);
$info = curl_getinfo($ch);
if(curl_error($ch)) {
    var_dump(curl_error($ch));
}

var_dump($res);
// string(14722) "<!DOCTYPE html><!--STATUS OK-->
// <html>
// <head>
// 	<meta http-equiv="content-type" content="text/html;charset=utf-8">
// 	<meta http-equiv="X-UA-Compatible" content="IE=Edge">
// 	<link rel="dns-prefetch" href="//s1.bdstatic.com"/>
// 	<link rel="dns-prefetch" href="//t1.baidu.com"/>
// 	<link rel="dns-prefetch" href="//t2.baidu.com"/>
// 	<link rel="dns-prefetch" href="//t3.baidu.com"/>
// 	<link rel="dns-prefetch" href="//t10.baidu.com"/>
// 	<link rel="dns-prefetch" href="//t11.baidu.com"/>
// 	<link rel="dns-prefetch" href="//t12.baidu.com"/>
// 	<link rel="dns-prefetch" href="//b1.bdstatic.com"/>
// 	< title > Baidu, you will know < / Title >
//  ........................
//  ........................
//  ........................
// </body></html>
// "

var_dump($info);
// array(37) {
//     ["url"]=>
//     string(21) "https://www.baidu.com"
//     ["content_type"]=>
//     string(9) "text/html"
//     ["http_code"]=>
//     int(200)
//     ["header_size"]=>
//     int(960)
//     ["request_size"]=>
//     int(52)
//     ["filetime"]=>
//     int(-1)
//     ["ssl_verify_result"]=>
//     int(0)
//     ["redirect_count"]=>
//     int(0)
//     ["total_time"]=>
//     float(0.127654)
//     ["namelookup_time"]=>
//     float(0.004669)
//     ["connect_time"]=>
//     float(0.030823)
//     ["pretransfer_time"]=>
//     float(0.100782)
//     ["size_upload"]=>
//     float(0)
//     ["size_download"]=>
//     float(14722)
//     ["speed_download"]=>
//     float(115921)
//     ["speed_upload"]=>
//     float(0)
//     ["download_content_length"]=>
//     float(14722)
//     ["upload_content_length"]=>
//     float(-1)
//     ["starttransfer_time"]=>
//     float(0.127519)
//     ["redirect_time"]=>
//     float(0)
//     ["redirect_url"]=>
//     string(0) ""
//     ["primary_ip"]=>
//     string(15) "183.232.231.172"
//     ["certinfo"]=>
//     array(0) {
//     }
//     ["primary_port"]=>
//     int(443)
//     ["local_ip"]=>
//     string(13) "192.168.51.11"
//     ["local_port"]=>
//     int(52795)
//     ["http_version"]=>
//     int(2)
//     ["protocol"]=>
//     int(2)
//     ["ssl_verifyresult"]=>
//     int(0)
//     ["scheme"]=>
//     string(5) "HTTPS"
//     ["appconnect_time_us"]=>
//     int(100710)
//     ["connect_time_us"]=>
//     int(30823)
//     ["namelookup_time_us"]=>
//     int(4669)
//     ["pretransfer_time_us"]=>
//     int(100782)
//     ["redirect_time_us"]=>
//     int(0)
//     ["starttransfer_time_us"]=>
//     int(127519)
//     ["total_time_us"]=>
//     int(127654)
//   }

curl_close($ch);

The standard CURL routine is actually three steps. curl_init() opens a handle, which contains the URL address and curl_exec() executes handle output or returns result, curl_close() closes the handle. Why CURL_ Is exec () output or return result? Because if by default, curl_exec() will print out the result directly like phpinfo(). We need to use curl_setopt() sets curlopt_ The constant return transfer is true or 1 to make curl_exec() returns the access result as a return value instead of directly outputting it. As can be seen, curl_setopt() is also a very important function in CURL. In fact, its function is to set various configuration parameters for the CURL handle, including curlopt we see in the code_ SSL_ Verifyhost and CURLOPT_SSL_VERIFYPEER is a configuration parameter prepared for HTTPS link access. CURL is also required for POST requests that we will see later_ Setopt().

curl_exec() returns the result of the URL accessed, curl_getinfo() returns some details of the request. For example, we can see the URL address, content type and HTTP address of the request_ Code and other information, which is very important for some business needs judgment. curl_error() is the display of error information in this request. If an error occurs, the error information can be obtained through this function.

POST request

The GET request is very simple. Of course, the POST request is not complex. As mentioned earlier, there are only some changes in the configuration parameters.

$ch = curl_init("http://localhost:9001");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt_array($ch, [
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => ['a'=>'post test'],
]);

$res = curl_exec($ch);
$info = curl_getinfo($ch);
if(curl_error($ch)) {
    var_dump(curl_error($ch));
}

var_dump($res);
// string(22) "test data post test"

curl_close($ch);

Here, we use a new function curl_setopt_array(), in fact, can be used more conveniently to define configuration parameters, and write curl one by one_ Setopt () is no different, but more convenient. We just need to specify CURLOPT_POST is true or 1, and then through CURLOPT_POSTFIELDS can assign a value to the POST parameter. Is it very simple.

URL encoding of CURL string

We have learned some coding related functions before. In CURL extension, there is also a corresponding URL coding function. In fact, it is not much different from using urlencode().

$ch = curl_init("http://localhost:9001");
$str = "Test code";
$escapeStr = curl_escape($ch, $str);
var_dump($escapeStr); // string(36) "%E6%B5%8B%E8%AF%95%E7%BC%96%E7%A0%81"
var_dump(curl_unescape($ch, $escapeStr)); // string(12) "test code"
curl_close($ch);

Use curl_escape() can URL encode the data using curl_unescape() can easily implement decoding. However, these two functions must have a CURL handle parameter, that is, they cannot be used directly without CURL. We'd better use more general functions such as urlencode() in our daily development.

View the version number of the CURL

Finally, let's learn a very simple function to check the CURL version of the current system and some related software information, such as the list of supported protocols.

var_dump(curl_version());
// array(16) {
//     ["version_number"]=>
//     int(475648)
//     ["age"]=>
//     int(5)
//     ["features"]=>
//     int(11519901)
//     ["ssl_version_number"]=>
//     int(0)
//     ["version"]=>
//     string(6) "7.66.0"
//     ["host"]=>
//     string(25) "x86_64-apple-darwin19.5.0"
//     ["ssl_version"]=>
//     string(14) "OpenSSL/1.1.1d"
//     ["libz_version"]=>
//     string(6) "1.2.11"
//     ["protocols"]=>
//     array(23) {
//       [0]=>
//       string(4) "dict"
//       [1]=>
//       string(4) "file"
//       [2]=>
//       string(3) "ftp"
//       [3]=>
//       string(4) "ftps"
//       [4]=>
//       string(6) "gopher"
//       [5]=>
//       string(4) "http"
//       [6]=>
//       string(5) "https"
//       [7]=>
//       string(4) "imap"
//       [8]=>
//       string(5) "imaps"
//       [9]=>
//       string(4) "ldap"
//       [10]=>
//       string(5) "ldaps"
//       [11]=>
//       string(4) "pop3"
//       [12]=>
//       string(5) "pop3s"
//       [13]=>
//       string(4) "rtmp"
//       [14]=>
//       string(4) "rtsp"
//       [15]=>
//       string(3) "scp"
//       [16]=>
//       string(4) "sftp"
//       [17]=>
//       string(3) "smb"
//       [18]=>
//       string(4) "smbs"
//       [19]=>
//       string(4) "smtp"
//       [20]=>
//       string(5) "smtps"
//       [21]=>
//       string(6) "telnet"
//       [22]=>
//       string(4) "tftp"
//     }
//     ["ares"]=>
//     string(6) "1.15.0"
//     ["ares_num"]=>
//     int(69376)
//     ["libidn"]=>
//     string(5) "2.2.0"
//     ["iconv_ver_num"]=>
//     int(0)
//     ["libssh_version"]=>
//     string(13) "libssh2/1.9.0"
//     ["brotli_ver_num"]=>
//     int(16777223)
//     ["brotli_version"]=>
//     string(5) "1.0.7"
//   }

summary

As mentioned at the beginning of the article, the content of CURL is not complex. The core is the steps. The most complex part is that there are a lot of configuration constant information, and these information is not easy to remember. Just master the commonly used ones. We will continue to explain other contents of CURL later. Don't miss it.

Test code: https://github.com/zhangyue0503/dev-blog/blob/master/php/2021/02/source/4. Learn the use of CURL extension function (I) php

Reference documents:

https://www.php.net/manual/zh/ref.curl.php