Curl is a PHP extension that allows you to transfer data or files between servers. Curl is a tool for transferring data and files between servers.

It is used to collect HTML web page files and interface data provided by other servers

Enable curl extension

(1) Enable curl in php.ini

(2) Save the installation path of PHP to the system variable of the environment variable (the separator between environment variables is the English semicolon)

(3) Restart the Apache server

(4) Restart the computer

Curl contains some common configuration items

(1) Use CURLOPT_RETURNTRANSFER configuration item to set whether to display the result directly (echo) or return the result (return)

(2) For HTTPS requests, the security certificate of the client needs to be verified. Usually, the authentication of the security certificate is skipped

(3) CURLOPT_HEADER Whether to return the header header

Curl method 1:

<? PHP /* * select * from url where url = ''; PHP /* * select * from url where url = ''; Private $is_return = 1; $is_return = 1; public function __set($p,$v) { if(property_exists($this, $p)){ $this->$p = $v; Public function send($data = array()) {//1\. $ch = curl_init(); $ch = curl_init(); Curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); $this-> curl_setopt($ch, $this-> CURLOPT_URL); //4\. Determine whether to get or post if(! empty($data)){ curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); If ($this->is_return=== =1){return curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); curl_close($ch); return $result; }else{// output curl_exec($ch); curl_close($ch); }}}Copy the code

Curl method 2:

/ / curl collector public function http_curl ($url, $type = 'get', $res = 'json', $arr = ' ') {/ / 1. $curl $ch=curl_init(); $curl ($ch, $CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); if($type=='post'){ curl_setopt($ch,CURLOPT_POST,1); curl_setopt($ch,CURLOPT_POSTFIELDS,$arr); $output=curl_exec($ch); / / 4. Close the curl_close ($ch); If ($res=='json'){if(curl_errno($ch)){return curl_error($ch); }else{// The request succeeded return json_decode($output,true); } } }//http_curl endCopy the code

Curl simulates file upload

Note: Before PHP5.6, upload files using: @

Later versions of Php5.6 use new CURLFile()

After the data is received by other servers, it can be moved

Curl simulates cookie login

(1) When we access the server, the server will first create a session file on the server side to save user information and facilitate data sharing on multiple pages. Then the server will tell the client to create a cookie on itself in the form of setCookie and save the name of the session file. In the past, when using the browser to access the server, the browser would create the cookie file on itself, now using our server to access: where to save the cookie?

CURLOPT_COOKIEJAR configuration item setting, where to save cookies

(2) When accessing the server in the future, take the cookie with you (inside is the name of the stored session file), then how to find this cookie?

The CURLOPT_COOKIEFILE configuration item sets which cookie file to carry with each request

Using CURL in PHP

CURL is a very powerful open source library that supports many protocols including HTTP, FTP, TELNET, etc. We use CURL to send HTTP requests. The benefits are that we have flexible options to set different HTTP protocol parameters and support for HTTPS. CURL specifies whether to encrypt the URL to be sent based on the URL prefix HTTP or HTTPS.

Using CURL to send a request

Using CURL to send an HTTP request requires the following steps:

  • Initialize the connection handle;
  • Set CURL option;
  • Execute and get the results;
  • Release the VURL connection handle.

The following program snippet is a typical procedure for sending HTTP using CURL

$ch = curl_init(); Curl_setopt ($ch,CURLOPT_URL,"http://www.devdo.net"); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_HEADER,0); $output = curl_exec($ch); if($output === FALSE ){ echo "CURL Error:".curl_error($ch); } // 4\. Release curl handle curl_close($ch);Copy the code

Four functions are used in the above code

Curl_init (); curl_close(); curl_close();

②curl_exec() performs the CURL request. If no error occurs, the function returns the data returned by the corresponding URL. This function returns FALSE if an error occurred. Note that the full equality sign is used to determine whether the output is FALSE. This is to distinguish between an empty string and an error.

The most important function in the CURL library is curl_setopt(), which allows you to customize HTTP requests by setting the options defined by the CURL library. Three important options are used in the above code snippet:

  • CURLOPT_URL Specifies the URL of the request;
  • CURLOPT_RETURNTRANSFER set to 1 means that the later curl_exec function returns the return string of the URL, rather than directing the return string to standard output and returning TRUE;
  • CURLLOPT_HEADER set to 0 to indicate that no HTTP header is returned.

You can go to the PHP web site to see a list of all the options supported by CURL.

Gets the output of a CURL request

After the curl_exec() function is executed, you can use the curl_getinfo() function to retrieve the output of the CURL request.

curl_exec($ch); $info = curl_getinfo($sh); Echo 'access'. $info [' url ']. 'takes'. $info [' total_time']. 'seconds';Copy the code

Curl_getinfo returns an associative array containing the following data:

  • Url: Indicates the network address.
  • Content_type: Content encoding.
  • Http_code: indicates the HTTP status code.
  • Header_size: indicates the size of the header.
  • Request_size: indicates the size of a request.
  • Filetime: indicates the time when a file is created.
  • Ssl_verify_result :SSL verification result.
  • Redirect_count: indicates the jump count.
  • Total_time: indicates the total time.
  • Namelookup_time :DNS query time.
  • Connect_time: time spent waiting for the connection.
  • Pretransfer_time: indicates the time required for preparing for transmission.
  • Size_uplpad: indicates the size of uploaded data.
  • Size_download: size of the data to be downloaded.
  • Speed_download: indicates the download speed.
  • Speed_upload: indicates the upload speed.
  • Download_content_length: indicates the length of the downloaded content.
  • Upload_content_length: indicates the length of the uploaded content.
  • Starttransfer_time: time for starting the transfer.
  • Redirect_time: indicates the redirection time.

The curl_getinfo() function also has an optional argument, opt, which can be used to set constants corresponding to this field. If the second argument is set, only the specified information is returned. For example, if you set opt, you can set constants that correspond to this field. If you set the second parameter, only the specified information is returned. For example, if you set opt to CURLINFO_TOTAL_TIME, the curl_getinfo() function only returns total_time, which is the total transfer time. When you only need to pay attention to some transfer information, it makes sense to set $opt.

Use CURL to send a GET request

Using CURL to send GET requests the key to sending GET requests is to assemble a properly formatted URL. Request address and GET data are composed of a “?” Split, then GET variable names and values are separated by “=”, and individual GET names and values are connected by “&”. PHP gives us a function specifically for assembling GET requests and data sections — http_build_query. This function takes an associative array and returns a STRING of GET requests described by the associated data. DoCurlGetRequest () {CURL (); doCurlGetRequest ();

** *@desc ** *@desc ** *@desc */ function doCurlGetRequest($url,$data,$timeout = 5){ if($curl == "" || $timeout <= 0){ return false; } $url = $url.'? '.http_bulid_query($data); $con = curl_init((string)$url); curl_setopt($con, CURLOPT_HEADER, false); curl_setopt($con, CURLOPT_RETURNTRANSFER,true); curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout); return curl_exec($con); }Copy the code

Using CURL, you can use CURL to send an HTTP request to the curl_init function.

Use CURL to send a POST request

To place the request in the body, you can use the CURLOPT_POSTFIELDS option provided by CURL. Set this option to POST string data. We also implement a function to send a POST request — doCurlPostRequest.

/** ** @desc Post request way * * / function doCurlPostRequest ($url, $requestString, $timeout = 5) {if ($url = = '| | $requestString = =' | | $timeout <=0){ return false; } $con = curl_init((string)$url); curl_setopt($con, CURLOPT_HEADER, false); curl_setopt($con, CURLOPT_POSTFIELDS, $requestString); curl_setopt($con, CURLOPT_POST,true); curl_setopt($con, CURLOPT_RETURNTRANSFER,true); curl_setopt($con, CURLOPT_TIMEOUT,(int)$timeout); return curl_exec($con); }Copy the code

In addition to setting CURLOPT_POSTFIELDS in the above code, we also set CURL_POST to true, identifying the request as a POST request. GET data can also be transmitted in a POST request, simply by assembling the GET request data in the URL.

[![attachments-2020-11-3ss2Emwo5fa8b2daa22ff.jpg](https://six.club/image/show/attachments-2020-11-3ss2Emwo5fa8b2daa22ff. jpg)](https://six.club/image/show/attachments-2020-11-3ss2Emwo5fa8b2daa22ff.jpg)
Source: https://www.cnblogs.com/lxj0205/p/9360826.html