PHP cURL request and example study notes

Source: Internet
Author: User
Tags curl oauth response code vars

Note:To use the curl_init function, you must enable this php extension.

1. Open php. ini and enable extension = php_curl.dll.
2. check php. which Directory is the extension_dir value of ini? Check whether php_curl.dll exists. If not, download php_curl.dll and copy libeay32.dll and ssleay32.dll in the php directory to c:/windows/system32.

Recently, when I learned about Tencent's open platform API interface, I saw a powerful PHP library-cURL. It is a file transfer tool that uses the URL syntax to work in the command line mode. This article was translated by a blogger from a foreign Blog. The original article address is http://codular.com/curl-with-php. This article is very basic, but it is well organized and has a systematic and comprehensive knowledge! (Some of the titles below are superfluous to the bloggers, so you can almost ignore them .)
1 Definition: What is cURL

CURL allows data transmission across a wide range of protocols and is a very powerful system. It is widely used to send data across websites, including API interaction and oAuth. CURL is almost omnipotent in its application scope, from basic HTTP requests to more complex FTP uploads or interactive verification of closed HTTPS websites. Let's take a look at the simple difference between sending a GET and POST request and processing the returned response, as well as some important parameter descriptions.

Before we perform anything through a cURL request, we first need to initialize a cURL instance. We can implement this by calling the curl_init () function, which returns a cURL resource. This function receives the request URL you want to send as a parameter. In this article, we will not proceed with this step. We can implement it in another way in the following process.
2 Note: some core settings

Once we get a cURL resource, we can start to make some configuration. The following lists some of the core settings I have summarized.

CURLOPT_RETURNTRANSFER-the response is returned as a string instead of being output to the screen.
CURLOPT_CONNECTTIMEOUT-connection timeout
CURLOPT_TIMEOUT-cURL execution timeout
CURLOPT_USERAGENT-the Useragent string used for the request
CURLOPT_URL-the URL object for sending the request
CURLOPT_POST-send a request in POST mode
CURLOPT_POSTFIELDS-array data in the POST-submitted request

3. Create a configuration

You can create a configuration by using curl_setopt (). In this way, three parameters are accepted: cURL resource, setting, and setting the corresponding value. Therefore, we can set the request URL we are sending as follows.

The code is as follows: Copy code

$ Curl = curl_init ();
Curl_setopt ($ curl, CURLOPT_URL, 'http: // www.111cn.net ');

As shown above, when getting cURL resources, we can set the URL by sending a parameter.

The code is as follows: Copy code

$ Curl = curl_init ('http: // www.111cn.net ');

Of course, you can also pass an array containing the variable name and variable value to the curl_setopt_array () function to create multiple configurations at a time.

The code is as follows: Copy code

$ Curl = curl_init ();
Curl_setopt_array ($ curl, array (
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http: // www.111cn.net'
));

4. Execute the request: curl_exec ()

After all the options are configured, we can execute the cURL request by calling curl_exec. This function will return three different situations:

The code is as follows: Copy code

$ Result = curl_exec ($ curl );

At this point, $ result already contains the response of the page-it may be JSON, a string or the HTML of a complete website.
5. Close the request: curl_close ()

After sending a request and getting the corresponding response, you need to close the cURL request to release some system resources. By calling the curl_close () method, we can release resources as easily as all other functions that need to use resources as parameters.
6 GET Requests

GET request is the default request method, and we can use it directly. In fact, all examples have been GET requests until now. If you want to add some parameters in the request, then you can like http://testcURL.com /? Like item1 = value & item2 = value2, these parameters are appended to the URL address as a query string.

Therefore, we can use the following example to send a GET request to the above URL and return the corresponding result.

The code is as follows: Copy code

// Get cURL resource
$ Curl = curl_init ();
// Set some options-we are passing in a useragent too here
Curl_setopt_array ($ curl, array (
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http: // testcURL.com /? Item1 = value & item2 = value2 ',
CURLOPT_USERAGENT => 'codular Sample cURL request'
));
// Send the request & save response to $ resp
$ Resp = curl_exec ($ curl );
// Close request to clear up some resources
Curl_close ($ curl );

7. POST request

The only difference in the syntax between GET requests and POST requests is that when you want to transmit some data, you have another setting. We will set CURLOPT_POST to true and transmit data containing an array by setting CURLOPT_POSTFIELDS.

Therefore, if we convert the above GET request to a POST request, we can use the following code:

The code is as follows: Copy code

// Get cURL resource
$ Curl = curl_init ();
// Set some options-we are passing in a useragent too here
Curl_setopt_array ($ curl, array (
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http: // www.111cn.net ',
CURLOPT_USERAGENT => 'codular Sample cURL request ',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array (
Item1 => 'value ',
Item2 => 'value2'
    )
));
// Send the request & save response to $ resp
$ Resp = curl_exec ($ curl );
// Close request to clear up some resources
Curl_close ($ curl );

Here, you have a POST request that will produce the same effect as the above GET request and send the returned data to the script, in this way, you can use them at will.

Example of initiating an https request

The code is as follows: Copy code

Function _ https_curl_post ($ url, $ vars)

Foreach ($ vars as $ key => $ value)
    {
$ Fields_string. = $ key. '='. $ value .'&';
    } 
$ Fields_string = substr ($ fields_string, 0, (strlen ($ fields_string)-1 ));
$ Ch = curl_init ();
Curl_setopt ($ ch, CURLOPT_URL, $ url );
Curl_setopt ($ ch, CURLOPT_SSL_VERIFYHOST, 2 );
Curl_setopt ($ ch, CURLOPT_SSL_VERIFYPEER, FALSE); // this line makes it work under https
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_POST, count ($ vars ));
Curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ fields_string );
$ Data = curl_exec ($ ch );
Curl_close ($ ch );
       
If ($ data)
    {
Return $ data;
    }
Else
    {
Return false;
    }
}

8 errors

Although we hate errors, you still need to pay attention to the possible situation when using cURL. Because you cannot ultimately control the website you send the request, and you cannot guarantee that the site's response results will be the way you expected, and the site will always be normal.

Here we provide two functions that can be used to handle errors:

Curl_error ()-returns a string error message (its value is blank when the request returns normally)
Curl_errno ()-return the number of cURL errors. Then you can view the page containing the error code.

For example, you can use the following example:

The code is as follows: Copy code

If (! Curl_exec ($ curl )){
Die ('Error: "'. curl_error ($ curl).'"-Code: '. curl_errno ($ curl ));
    }

If you want any HTTP response code greater than 400 to generate an error, instead of returning the entire HTML page, you can set CURLOPT_FAILONERROR to true. CURL is a huge object, and there are many possibilities. Some websites may provide service pages for some user proxies. When using API interfaces, they may require you to send a special user proxy. If you still want to know some cURL requests, why not try oAuth with Instagram?

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.