How to use cURL in PHP
Today we will explore the cURL extension in PHP, which allows you to make HTTP requests from code.
In daily PHP development, you often need to communicate with external websites. Whether you're calling a third-party REST API to get data or downloading resources from an external website, you need a library that can do it easily.
In PHP, you can use different methods to connect and communicate with different types of servers. One of the simplest methods is to read a remote file using the file_get_contents
function. On the other hand, sockets can also be used to communicate between the client and the server. However, in this article, we will discuss cURL extensions in detail with practical examples.
cURL stands for Client URL and is a library that allows you to send and receive information using URL syntax. In fact, it leverages the libcurl library created by Daniel Stenberg, which allows you to connect to and communicate with many different types of servers using many different types of protocols. In addition to HTTP and HTTPS, the libcurl library supports protocols such as FTP, Gopher, Telnet, DICT, File, and LDAP.
Starting in the next section, we will demonstrate how to use the cURL function in PHP through several practical examples.
Real world examples
In this section, we will build real-life examples to demonstrate the various cURL functions in PHP.
How to download files using cURL in PHP
Reading or downloading remote files is one of the most common use cases for cURL. This is done via a cURL GET request, which we will discuss in this section.
Proceed to create the curl_read_file.php file with the following content.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
In the above example, we use the cURL function to read the home page of the example.com domain. Let’s go through the important snippets to understand how it works.
First, we use the curl_init
function to initialize a new cURL session. The $curlHandle
variable stores a cURL handle. We can use the curl_setopt
function to set various options for cURL transmission.
When you use cURL, the function you will use most often is the curl_setopt
function, because it allows you to initialize various CURLOPT_*
request options. The curl_setopt
function takes three parameters: the cURL handle, the CURLOPT_XXX
option, and the value of the CURLOPT_XXX
option.
Next, we set the request URL to example.com
via the curl_setopt
function using the CURLOPT_URL
option. Additionally, we set the CURLOPT_RETURNTRANSFER
option to TRUE
because we want the response to be initialized into the $responseData
variable. If we don't set it to TRUE
, the response will be displayed directly on the screen. Finally, we set the CURLOPT_HEADER
option to FALSE
to skip header information in the output.
Finally, we use the curl_exec
function to execute the cURL request. If all goes well, the $responseData
variable should contain the source code for the example.com
home page.
How to post data using cURL in PHP
In this section, we will learn how to post data using cURL.
Let's create the curl_post_example.php file with the following content.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
In the above example, we assume that the request needs to be submitted using the HTTP POST method. In fact, it works similarly to submitting a form using the POST method.
$fields
Variable contains the array of values we need to submit as POST data. Next, we use the http_build_query
function to prepare the URL-encoded query string.
Next, we set the CURLOPT_POST
option to TRUE
to set the request method to HTTP POST. Additionally, we need to use the CURLOPT_POSTFIELDS
option to set the POST data we want to submit with the request.
Finally, we use the curl_exec
function to execute the cURL request. This will allow you to make a cURL POST request.
How to post JSON data using cURL in PHP
Typically, you need to submit JSON data in a cURL POST request. In this section, we will learn how to submit JSON data using the POST method in a cURL request.
Since this is a POST request, let's modify the example discussed in the previous section. Proceed to create the curl_post_json.php file with the following content.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
Although it looks similar to the example in the previous section, the important thing is that we use the json_encode
function to create a JSON string from the $fields
array.
接下来,我们使用 CURLOPT_HTTPHEADER
选项将 Content-Type
标头设置为 application/json
以通知 API 服务器我们正在发送 JSON 数据。 Content-Type
标头对于以不同格式发布数据非常有用。例如,如果您想发送 XML 数据,则必须将 Content-Type
标头设置为 application/xml
。
除此之外,它与常规 POST 请求几乎相同。所以这样一来,就可以通过设置适当的 Content-Type
header 来发布不同类型的数据。如果您不设置 Content-Type
标头,它将使用 application/x-www-form-urlencoded
作为默认值。
如何在 PHP 中使用 cURL 上传文件
在本节中,我们将讨论如何使用 cURL 上传文件。
让我们创建包含以下内容的 curl_post_file.php 文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
当你要上传文件时,你需要首先创建一个 CURLFile
对象。从 PHP 5.5+ 开始,创建它相当容易,因为您只需要使用 curl_file_create
函数来创建 CURLFile
对象。 curl_file_create
函数的第一个参数是要上传的文件的绝对路径。
如果您仍在使用较旧的 PHP 版本(不推荐),我们已使用后备 '@' 。 realpath('/absolute/path/to/file/')
语法创建文件链接。
最后,我们将 Content-Type
标头设置为 multipart/form-data
,因为它将是一个多部分表单 POST 请求。除此之外,这是一个例行的 cURL POST 请求。
到目前为止,我们已经了解了 PHP 中经常使用的几种不同的 cURL 方法。在下一节中,我们将了解如何使用 Guzzle 库,它使您在 PHP 中处理 HTTP 请求时变得更加轻松。
什么是 Guzzle HTTP 客户端?
根据官方文档:
Guzzle 是一个 PHP HTTP 客户端,可以轻松发送 HTTP 请求,并且可以轻松地与 Web 服务集成。
让我们快速了解一下使用 Guzzle 相对于 cURL PHP 函数的优势:
- 适用于不同类型数据的简单界面
- 支持同步和异步请求
- 支持 cURL、套接字和 PHP 流
- 符合 PSR-7
- 还有更多
总而言之,当您想使用不同的方法进行 HTTP 调用时,它是最好的库之一。在本节中,我们将讨论如何安装 Guzzle,然后通过几个快速示例来演示该库的强大功能!
如何安装 Guzzle 库
官方文档建议您使用Composer来安装Guzzle。让我们运行以下命令在您的项目中安装 Guzzle。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
安装后,您需要使用 Composer 的自动加载器,如以下代码片段所示。
1 |
|
这样,您就可以使用 Guzzle 了!
如何使用 Guzzle 发出 GET 请求
在本节中,我们将了解如何使用 Guzzle 发送 GET 请求。
我们将修改之前讨论的示例,因为它将帮助您了解如何将现有的 cURL PHP 代码转换为基于 Guzzle 的实现。
让我们看一下修改后的示例。
1 2 3 4 5 6 7 |
|
是不是很简单呢?我们创建了 \GuzzleHttp\Client
类的实例,并将其分配给 $client
变量。现在,您可以访问 \GuzzleHttp\Client
类提供的大量实用方法。
在我们的例子中,我们需要使用 GET 方法获取内容,因此我们使用了 \GuzzleHttp\Client
类的 get
方法,它将返回 GuzzleHttp\Psr7\Response
对象。 GuzzleHttp\Psr7\Response
对象提供了各种方法,如 getStatusCode
、getBody
、getReasonPhrase
等。我们使用 getBody
方法来获取响应正文内容。
这就是您如何使用 Guzzle 执行 HTTP GET 请求。
如何使用 Guzzle 发出 POST 请求
在本节中,我们将了解如何使用 Guzzle 执行 HTTP POST 请求。
我们将修改我们在前面部分中讨论过的 curl_post_example.php 示例。使用 Guzzle 修改后的代码如下所示。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
由于这是一个 POST 请求,因此我们需要传递 $options
数组作为 post
方法的第二个参数。在我们的示例中,它包含我们需要作为 POST 数据提交的表单数据。
如果您想知道如何发送 JSON 数据,只需将 form_params
键更改为 json
,数据就会以 JSON 形式发送!
此外,如果您想随请求一起发送任何 HTTP 标头,您可以使用 headers
键来完成,如以下代码片段所示。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
事实上,Guzzle 库为每种方法提供了很多配置选项。此外,做同一件事有多种方法,所以我鼓励您详细探索它,我相信它会很有趣!
这是对 Guzzle 库以及 PHP cURL 函数的快速介绍。
结论
今天,我们探讨了 PHP 中 cURL 扩展的基础知识。我们讨论了如何在 PHP 中使用 cURL 执行不同类型的 HTTP 请求。此外,我们还快速介绍了 Guzzle 库,它使开发人员在 PHP 中处理 HTTP 请求时更加轻松。
The above is the detailed content of How to use cURL in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





Alipay PHP...

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,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

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.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
