Home >Backend Development >PHP Tutorial >cURL request and sample study notes in PHP_PHP tutorial

cURL request and sample study notes in PHP_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:49:091226browse

cURL is a very powerful function in PHP. It can imitate various user requests, such as imitating user login, sending PHP cookies and other operations. Let me sort out some related methods and share them with you

Remarks:To use the curl_init function, this php extension must be turned on.

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

Recently, in the process of learning the API interface of Tencent Open Platform, I saw a very powerful PHP library-cURL. It is a file transfer tool that uses URL syntax to work in command line mode. This article was translated directly by the blogger from a foreign blog. The original address is: http://codular.com/curl-with-php. This article is very basic, but the organization is very clear, and the knowledge is relatively systematic and comprehensive, so I turned it over and saved it! (Some of the titles below are superfluous by bloggers and can be ignored by everyone.)
1 Definition: What is cURL

cURL allows data transfer across a wide range of protocols and is a very powerful system. It is widely used for sending data across websites, including things like API interactions and oAuth. cURL is almost omnipotent in its scope of applications, from basic HTTP requests, to more complex FTP uploads or interactive authentication of closed HTTPS websites. Let's take a look at the simple differences between sending a GET and POST request and handling the returned response, as well as some important parameter descriptions.

Before we can do anything with a cURL request, we first need to initialize an instance of cURL. We can achieve this by calling the curl_init() function, which will return a cURL resource. This function receives as one of its parameters the request URL you want to send. In this article, we will not do this step first, and we can implement it in another way in the following process.
2 Notes: Some core settings

Once we get a cURL resource, we can start doing some configuration. Some of the core settings I summarized are listed below.

CURLOPT_RETURNTRANSFER - Returns the response as a string instead of outputting to the screen
CURLOPT_CONNECTTIMEOUT - Connection timeout time
CURLOPT_TIMEOUT - cURL execution timeout
CURLOPT_USERAGENT - Useragent string used for the request
CURLOPT_URL - the URL object to send the request
CURLOPT_POST - Send a request as POST
CURLOPT_POSTFIELDS - Array data in the POST submitted request

3 Create a configuration

We can create a configuration by using the curl_setopt() method, which accepts 3 parameters: cURL resource, setting and setting corresponding value. So we can set the request URL we are sending as shown below.

The code is as follows Copy code
 代码如下 复制代码

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, 'http://www.bKjia.c0m');

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, 'http://www.bKjia.c0m');

 代码如下 复制代码

    $curl = curl_init('http://www.hzhuti.com');

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

The code is as follows Copy code
$curl = curl_init('http://www.hzhuti.com');
 代码如下 复制代码

    $curl = curl_init();
    curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://www.bKjia.c0m'
    ));

Of course, we can also create multiple configurations at once by passing an array containing variable names and variable values ​​to the curl_setopt_array() function.
The code is as follows Copy code
$curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => 'http://www.bKjia.c0m' ));

4 Execution request: curl_exec()

When all options are configured and ready to send a request, we can execute this cURL request by calling curl_exec(). This function will return three different situations:

The code is as follows Copy code
 代码如下 复制代码

    $result = curl_exec($curl);

$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 request: curl_close()


After you send a request and get the corresponding return result, you need to close the cURL request to release some system resources. By calling the curl_close() method, we can release the resource simply like any other function that requires a resource as a parameter. 6 GET request

GET request is the default request method, and we can use it very straightforwardly. Virtually all of the examples so far have been GET requests. If you want to add some parameters to the request, then you can append these parameters to the URL address as a query string like http://testcURL.com/?item1=value&item2=value2.

Therefore, we can send a GET request to the above URL through the following example and return the corresponding result.
 代码如下 复制代码

    // 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);

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'

));
 代码如下 复制代码

    // 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.bKjia.c0m',
    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);

// Send the request & save response to $resp $resp = curl_exec($curl); // Close request to clear up some resources curl_close($curl);
7 POST requests The only difference in syntax between GET request and POST request is: when you want to send some data, there is an additional setting. We will set CURLOPT_POST to true and send data containing an array by setting CURLOPT_POSTFIELDS. So, if we convert the above GET request into 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.bKjia.c0m', 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);

At this point, you have a POST request: it will produce the same effect as the GET request above, and will return the data to the script so that you can use them as you like.

Example of making https request

$data = curl_exec($ch); $data = curl_exec($ch); curl_close($ch);

The code is as follows
 代码如下 复制代码

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

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
 代码如下 复制代码

    if(!curl_exec($curl)){
    die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
    }

curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

curl_setopt($ch, CURLOPT_POST, count($vars) );

Curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
                              If ($data)

{

          return $data; else {          return false; } } 8 Error
As much as we hate mistakes, you still have to be aware of situations that may arise when using cURL. Because you ultimately have no control over the website you send the request to, and there is no guarantee that the site's response will be the way you expected and that the site will always be in a normal state.
Here are two functions that can be used to handle errors: curl_error() - Returns a string error message (when the request returns normally, its value is empty) curl_errno() - Returns the number of cURL errors, and 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, then you can set CURLOPT_FAILONERROR to true. cURL is a giant, and there are many, many possibilities. Some websites may provide service pages for some user agents. When using the API interface, they may require you to send a special user agent. These are all things we need to pay attention to. If you still want to learn about cURL requests, why not try oAuth with Instagram? http://www.bkjia.com/PHPjc/632735.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632735.htmlTechArticlecURL is a very powerful function in php, which can imitate various user requests, such as imitating user login and sending php Cookie and other operations, let me sort out some related methods for you to read...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn