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

Jul 13, 2016 am 10:49 AM
curl php Function Can study yes imitate Example notes ask

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles