Use Curl in PHP to send requests (get requests and post requests)

Source: Internet
Author: User
Tags how to use curl
This article mainly introduces the use of curl in PHP to send requests (get requests and post requests), small series feel very good, and now share to everyone, but also for everyone to do a reference. Let's take a look at it with a little knitting.

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. Initialize the connection handle;

2. Set the Curl option;

3. Implement and obtain results;

4. Release 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 URL curl_setopt ($ch, Curlopt_url, "http://www.devdo.net"); curl_setopt ($ch, curlopt_returntransfer,1); curl_setopt ($ch, curlopt_header,0); 3. Executes and obtains the contents of the HTML document $output = curl_exec ($ch); if ($output = = = FALSE) {echo "CURL Error:". Curl_error ($ch);} 4. Release Curl handle Curl_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:

①CURLOPT_URL Specifies the URL of the request;

②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;

③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.cn/).

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 enclosing the calling interface of curl, GET request mode. */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);}


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 encapsulates the calling interface of curl, the way the post is requested **/function Docurlpostrequest ($url, $requestString, $timeout = 5) {if ($url = = "| | $requ eststring = = "| | $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); }


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.

The above is the whole content of this article, I hope that everyone's learning has helped, but also hope that we support topic.alibabacloud.com.

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.