PHP uses Curl to explain

Source: Internet
Author: User
Tags curl options how to use curl

Curl is a very powerful open source library that supports many protocols, including HTTP, FTP, Telnet, and so on, which we use to send HTTP requests. The advantage of this is that we can set different HTTP protocol parameters with flexible options and support HTTPS. Curl can automatically choose whether or not to encrypt the sent content based on if the URL prefix is "HTTP" or "HTTPS".

Basic process for sending requests using curl

A PHP extension that uses Curl to complete the sending of an HTTP request generally has the following steps:

    1. Initializes the connection handle;
    2. Set curl options;
    3. Execute and obtain results;
    4. Releases the Vurl connection handle.

The following program fragment is a typical process for sending HTTP using Curl

//1. Initialize $ch=curl_init ();//2. Set options, including URLcurl_setopt ($ch, Curlopt_url, "Http://www.devdo.net"); curl_setopt ($ch, curlopt_returntransfer,1); curl_setopt ($ch, curlopt_header,0); //3. Execute and get HTML document content $output= Curl_exec ($ch); if($output===FALSE ){ Echo"CURL Error:". Curl_error ($ch); } //4. Release the curl handleCurl_close ($ch);

Four functions are used in the above code

    • Curl_init () and Curl_close () are simple to initialize curl connections and turn off curl connections, respectively.
    • Curl_exec () performs a curl request, and if no error occurs, the return of the function is the data returned by the corresponding URL, satisfied with the string, or False if an error occurs. It is important to note that it is the full equals sign to determine whether the output is false, in order to differentiate between returning an empty string and an error.
    • The most important function in the Curl Library is curl_setopt (), which can customize the HTTP request by setting the options defined by the Curl function library. Three important options are used in the code snippet above:
      1. CURLOPT_URL Specifies the URL of the request;
      2. Curlopt_returntransfer set to 1 means that the return of the curl_exec function that is executed later is the return string of the URL, instead of directing the return string to the standard output and returning true;
      3. Curllopt_header set to 0 indicates that HTTP header information is not returned.

There are many options for curl, and you can see a list of all the options that Curl supports on the PHP official website (http://www.php.net/manual/en/function.curl-setopt.php).

Get output information for a Curl request

After the curl_exec () function executes, you can use the Curl_getinfo () function to obtain information about the output of the curl request, as shown in the following example code:

Curl_exec ($ch); $info = curl_getinfo ($sh); Echo ' Get '. $info [' url ']. ' Time-consuming '. $info [' Total_time ']. ' Seconds ';

In the code above, Curl_getinfo returns an associative array containing the following data:

  • URL: Network address.
  • Content_Type: Content encoding.
  • Http_code:http status Code.
  • The size of the header_size:header.
  • Request_size: The size of the request.
  • FILETIME: The time the file was created.
  • SSL_VERIFY_RESULT:SSL validation results.
  • Redirect_count: Jump Count.
  • Total_time: Total time-consuming.
  • Namelookup_time:dns query time-consuming.
  • Connect_time: Wait for the connection to take time.
  • Pretransfer_time: Preparation time before transmission.
  • Size_uplpad: The size of the uploaded data.
  • Size_download: The size of the downloaded data.
  • Speed_download: Download speed.
  • Speed_upload: Upload speed.
  • Download_content_length: The length of the downloaded content.
  • Upload_content_length: The length of the uploaded content.
  • Starttransfer_time: Start the transfer schedule.
  • Redirect_time: Redirection time-consuming.

The Curl_getinfo () function also has an optional parameter $opt, which allows you to set some constants that correspond to the field above, and if the second parameter is set, only the specified information is returned. For example, if you set $opt to Curlinfo_total_time, the Curl_getinfo () function returns only Total_time, that is, the total transfer time, and setting the $opt parameter is meaningful when you only need to focus on certain transmission information.

Send a GET request using curl

How to use curl to send a GET request, the key to sending a GET request is to assemble a properly formatted URL. Request address and get data by a "?" The name and value of the get variable are separated by "=", and each get name and value is connected by "&". PHP provides us with a function to assemble the GET request and Data section--http_build_query, which takes an associative array and returns a GET request string that is described by the associated data. Using this function, the general process of sending HTTP requests in conjunction with Curl, we closed a function--docurlgetrequest to send a GET request, with the following code:

** *@desc The calling interface of the enclosing curl, the GET request method. */functionDocurlgetrequest ($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); returnCurl_exec ($con);}

This function passes the URL with the get parameter assembled with Http_build_query to the Curl_init function, and then uses Curl to send the HTTP request.

Send a POST request using Curl

You can use the option Curlopt_postfields provided by Curl to set this option as the post string data to place the request in the body. We also implemented a function--docurlpostrequest to send a POST request, with the following code:

/** * * @desc Package Curl's calling interface, POST request method **/functionDocurlpostrequest ($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); returnCurl_exec ($con); }

In addition to setting curlopt_postfields in the above code, we also set Curl_post to True, which identifies the request as a POST request. You can also transfer get data in a POST request, just assemble the GET request data in the URL.

PHP uses Curl to explain

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.