Home Backend Development PHP Tutorial From start to finish: How to use php extension cURL to make HTTP requests

From start to finish: How to use php extension cURL to make HTTP requests

Jul 29, 2023 pm 05:07 PM
curl http request Expand

From start to finish: How to use php extension cURL for HTTP requests

Introduction:
In web development, it is often necessary to communicate with third-party APIs or other remote servers. Using cURL to make HTTP requests is a common and powerful way. This article will introduce how to use PHP to extend cURL to perform HTTP requests, and provide some practical code examples.

1. Preparation
First, make sure that php has the cURL extension installed. You can execute php -m | grep curl on the command line to check whether it is installed. If it is not installed, you can install it by following the steps below:

  1. On Linux systems, use the following command to install the cURL extension:
    sudo apt-get install php-curl
  2. On Windows systems, edit the php.ini file, find the line extension=php_curl.dll, and remove the comment symbol (;).
  3. Restart the web server, such as Apache or Nginx.

2. Perform GET request
GET request is the most common HTTP request type. Here is a sample code that uses cURL to perform a GET request:

$url = 'https://api.example.com/users';
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

if ($response === false) {
    echo '请求失败';
} else {
    echo '响应内容:' . $response;
}
Copy after login

The above code first initializes the cURL session, sets the requested URL, and sets some options through the curl_setopt function. Among them, the CURLOPT_RETURNTRANSFER option is used to set the response result to be returned instead of outputting it directly to the screen. Then, use the curl_exec function to send the request and get the response result. Finally, close the session through the curl_close function.

3. Execute POST request
POST request is mainly used to submit data to the server, such as form data, etc. The following is a sample code that uses cURL to perform a POST request:

$url = 'https://api.example.com/users';
$fields = array(
    'name' => 'John Doe',
    'email' => 'john@example.com'
);

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));

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

if ($response === false) {
    echo '请求失败';
} else {
    echo '响应内容:' . $response;
}
Copy after login

In addition to setting the CURLOPT_POST option to true, the above code also uses the CURLOPT_POSTFIELDS option to set the POST request. data. The http_build_query function is used here to convert the array into a string in URL parameter format.

4. Processing the response
In HTTP requests, it is often necessary to check the status code of the response to determine whether the request is successful, and to process the returned data. Here is a sample code that demonstrates how to handle the response:

$url = 'https://api.example.com/users';
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

if ($httpCode == 200) {
    // 请求成功
    $data = json_decode($response, true);
    // 处理返回的数据
} else {
    // 请求失败
    echo '请求失败,状态码:' . $httpCode;
}
Copy after login

The code above uses the curl_getinfo function to get the transfer information, including the HTTP status code. Determine whether the request is successful based on the status code, and process the returned data according to requirements.

5. Set other options
cURL provides many other options to meet more complex needs. The following are some commonly used options:

  1. CURLOPT_HEADER: Set whether to return response headers, the default is false.
  2. CURLOPT_TIMEOUT: Set the request timeout in seconds. The default is 0, which means there is no timeout limit.
  3. CURLOPT_USERAGENT: Set the User-Agent header to simulate the browser identity.
  4. CURLOPT_SSL_VERIFYPEER: Set whether to verify the server SSL certificate. The default is true.

6. Summary
This article introduces how to use php to extend cURL to make HTTP requests, and provides some practical code examples. By mastering the use of cURL, you can easily communicate with the remote server and obtain the required data. At the same time, pay attention to security and error handling to ensure the reliability of requests.

Finally, I hope readers can learn the basic knowledge about cURL through this article and use it flexibly in actual development. Thanks for reading!

The above is the detailed content of From start to finish: How to use php extension cURL to make HTTP requests. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Tutorial on updating curl version under Linux! Tutorial on updating curl version under Linux! Mar 07, 2024 am 08:30 AM

To update the curl version under Linux, you can follow the steps below: Check the current curl version: First, you need to determine the curl version installed in the current system. Open a terminal and execute the following command: curl --version This command will display the current curl version information. Confirm available curl version: Before updating curl, you need to confirm the latest version available. You can visit curl's official website (curl.haxx.se) or related software sources to find the latest version of curl. Download the curl source code: Using curl or a browser, download the source code file for the curl version of your choice (usually .tar.gz or .tar.bz2

From start to finish: How to use php extension cURL to make HTTP requests From start to finish: How to use php extension cURL to make HTTP requests Jul 29, 2023 pm 05:07 PM

From start to finish: How to use php extension cURL for HTTP requests Introduction: In web development, it is often necessary to communicate with third-party APIs or other remote servers. Using cURL to make HTTP requests is a common and powerful way. This article will introduce how to use PHP to extend cURL to perform HTTP requests, and provide some practical code examples. 1. Preparation First, make sure that php has the cURL extension installed. You can execute php-m|grepcurl on the command line to check

Cause analysis: HTTP request error 504 gateway timeout Cause analysis: HTTP request error 504 gateway timeout Feb 19, 2024 pm 05:12 PM

Brief introduction to the reason for the http request error: 504GatewayTimeout: During network communication, the client interacts with the server by sending HTTP requests. However, sometimes we may encounter some error messages during the process of sending the request. One of them is the 504GatewayTimeout error. This article will explore the causes and solutions to this error. What is the 504GatewayTimeout error? GatewayTimeo

Solution: Socket Error when handling HTTP requests Solution: Socket Error when handling HTTP requests Feb 25, 2024 pm 09:24 PM

http request error: Solution to SocketError When making network requests, we often encounter various errors. One of the common problems is SocketError. This error is thrown when our application cannot establish a connection with the server. In this article, we will discuss some common causes and solutions of SocketError. First, we need to understand what Socket is. Socket is a communication protocol that allows applications to

Extensions and third-party modules for PHP functions Extensions and third-party modules for PHP functions Apr 13, 2024 pm 02:12 PM

To extend PHP function functionality, you can use extensions and third-party modules. Extensions provide additional functions and classes that can be installed and enabled through the pecl package manager. Third-party modules provide specific functionality and can be installed through the Composer package manager. Practical examples include using extensions to parse complex JSON data and using modules to validate data.

Set query parameters for HTTP requests using Golang Set query parameters for HTTP requests using Golang Jun 02, 2024 pm 03:27 PM

To set query parameters for HTTP requests in Go, you can use the http.Request.URL.Query().Set() method, which accepts query parameter names and values ​​as parameters. Specific steps include: Create a new HTTP request. Use the Query().Set() method to set query parameters. Encode the request. Execute the request. Get the value of a query parameter (optional). Remove query parameters (optional).

How to handle 301 redirection of web pages in PHP Curl? How to handle 301 redirection of web pages in PHP Curl? Mar 08, 2024 am 11:36 AM

How to handle 301 redirection of web pages in PHPCurl? When using PHPCurl to send network requests, you will often encounter a 301 status code returned by the web page, indicating that the page has been permanently redirected. In order to handle this situation correctly, we need to add some specific options and processing logic to the Curl request. The following will introduce in detail how to handle 301 redirection of web pages in PHPCurl, and provide specific code examples. 301 redirect processing principle 301 redirect means that the server returns a 30

How to install mbstring extension under CENTOS7? How to install mbstring extension under CENTOS7? Jan 06, 2024 pm 09:59 PM

1.UncaughtError:Calltoundefinedfunctionmb_strlen(); When the above error occurs, it means that we have not installed the mbstring extension; 2. Enter the PHP installation directory cd/temp001/php-7.1.0/ext/mbstring 3. Start phpize(/usr/local/bin /phpize or /usr/local/php7-abel001/bin/phpize) command to install php extension 4../configure--with-php-config=/usr/local/php7-abel

See all articles