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.
In this section, we will build real-life examples to demonstrate the various cURL functions 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.
<?php $url = 'https://www.example.com'; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HEADER, false); $data = curl_exec($curl); curl_close($curl);
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.
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.
<?php $url = '{POST_REST_ENDPOINT}'; $curl = curl_init(); $fields = array( 'field_name_1' => 'Value 1', 'field_name_2' => 'Value 2', 'field_name_3' => 'Value 3' ); $fields_string = http_build_query($fields); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, TRUE); curl_setopt($curl, CURLOPT_POSTFIELDS, $fields_string); $data = curl_exec($curl); curl_close($curl);
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.
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.
<?php $url = '{POST_REST_ENDPOINT}'; $curl = curl_init(); $fields = array( 'field_name_1' => 'Value 1', 'field_name_2' => 'Value 2', 'field_name_3' => 'Value 3' ); $json_string = json_encode($fields); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, TRUE); curl_setopt($curl, CURLOPT_POSTFIELDS, $json_string); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true ); $data = curl_exec($curl); curl_close($curl);
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
作为默认值。
在本节中,我们将讨论如何使用 cURL 上传文件。
让我们创建包含以下内容的 curl_post_file.php 文件。
<?php $url = '{POST_REST_ENDPOINT}'; $curl = curl_init(); if (function_exists('curl_file_create')) { $fileAttachment = curl_file_create('/absolute/path/to/file/'); } else { $fileAttachment = '@' . realpath('/absolute/path/to/file/'); } $fields = array( 'field_name_1' => 'Value 1', 'field_name_2' => 'Value 2', 'field_name_3' => 'Value 3', 'uploaded_file' => $fileAttachment ); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, TRUE); curl_setopt($curl, CURLOPT_POSTFIELDS, $fields); curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); $data = curl_exec($curl); curl_close($curl);
当你要上传文件时,你需要首先创建一个 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 是一个 PHP HTTP 客户端,可以轻松发送 HTTP 请求,并且可以轻松地与 Web 服务集成。
让我们快速了解一下使用 Guzzle 相对于 cURL PHP 函数的优势:
总而言之,当您想使用不同的方法进行 HTTP 调用时,它是最好的库之一。在本节中,我们将讨论如何安装 Guzzle,然后通过几个快速示例来演示该库的强大功能!
官方文档建议您使用Composer来安装Guzzle。让我们运行以下命令在您的项目中安装 Guzzle。
$composer require guzzlehttp/guzzle:^7.0 ./composer.json has been created Loading composer repositories with package information Updating dependencies (including require-dev) Package operations: 6 installs, 0 updates, 0 removals - Installing psr/http-message (1.0.1): Loading from cache - Installing psr/http-client (1.0.1): Loading from cache - Installing ralouphie/getallheaders (3.0.3): Loading from cache - Installing guzzlehttp/psr7 (1.7.0): Loading from cache - Installing guzzlehttp/promises (1.4.1): Loading from cache - Installing guzzlehttp/guzzle (7.2.0): Loading from cache guzzlehttp/psr7 suggests installing laminas/laminas-httphandlerrunner (Emit PSR-7 responses) guzzlehttp/guzzle suggests installing psr/log (Required for using the Log middleware) Writing lock file Generating autoload files
安装后,您需要使用 Composer 的自动加载器,如以下代码片段所示。
require 'vendor/autoload.php';
这样,您就可以使用 Guzzle 了!
在本节中,我们将了解如何使用 Guzzle 发送 GET 请求。
我们将修改之前讨论的示例,因为它将帮助您了解如何将现有的 cURL PHP 代码转换为基于 Guzzle 的实现。
让我们看一下修改后的示例。
<?php require 'vendor/autoload.php'; $client = new \GuzzleHttp\Client(); $response = $client->get('https://example.com'); $responseContents = $response->getBody();
是不是很简单呢?我们创建了 \GuzzleHttp\Client
类的实例,并将其分配给 $client
变量。现在,您可以访问 \GuzzleHttp\Client
类提供的大量实用方法。
在我们的例子中,我们需要使用 GET 方法获取内容,因此我们使用了 \GuzzleHttp\Client
类的 get
方法,它将返回 GuzzleHttp\Psr7\Response
对象。 GuzzleHttp\Psr7\Response
对象提供了各种方法,如 getStatusCode
、getBody
、getReasonPhrase
等。我们使用 getBody
方法来获取响应正文内容。
这就是您如何使用 Guzzle 执行 HTTP GET 请求。
在本节中,我们将了解如何使用 Guzzle 执行 HTTP POST 请求。
我们将修改我们在前面部分中讨论过的 curl_post_example.php 示例。使用 Guzzle 修改后的代码如下所示。
<?php require 'vendor/autoload.php'; $client = new \GuzzleHttp\Client(); $options = [ 'form_params' => [ "field_name_1" => "Value 1", "field_name_2" => "Value 2", "field_name_3" => "Value 3", ] ]; $response = $client->post("{POST_REST_ENDPOINT}", $options); $responseContents = $response->getBody(); ?>
由于这是一个 POST 请求,因此我们需要传递 $options
数组作为 post
方法的第二个参数。在我们的示例中,它包含我们需要作为 POST 数据提交的表单数据。
如果您想知道如何发送 JSON 数据,只需将 form_params
键更改为 json
,数据就会以 JSON 形式发送!
此外,如果您想随请求一起发送任何 HTTP 标头,您可以使用 headers
键来完成,如以下代码片段所示。
... ... $headers = array( 'Content-Type' => 'application/json' ); $options = [ 'form_params' => [ "field_name_1" => "Value 1", "field_name_2" => "Value 2", "field_name_3" => "Value 3", ], ‘headers’ => $headers ]; ... ...
事实上,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!