Home > Article > Backend Development > cURL library in PHP
This article introduces to you the cURL library in PHP. Now I share it with you. Friends in need can refer to it
When originally designed, cURL (Client URL Library) was a command line tool for transferring data using URL syntax. Through the cURL library, we can freely use a certain protocol in PHP scripts to obtain or submit data, such as obtaining HTTP request data. Simply put, cURL is a tool for clients to request resources from servers.
PHP supports the libcurl library created by Daniel Stenberg, which can connect and communicate with various servers and use various protocols. The protocols currently supported by libcurl include http, https, ftp, gopher, telnet, dict, file, and ldap. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP upload (can also be completed through PHP's FTP extension), HTTP form-based upload, proxy, cookies, and username and password authentication.
In PHP, it is actually very simple to get the content of a URL. There are many ways to achieve it, such as using file_get_contents()
Function:
<?php $content = file_get_contents("https://segmentfault.com"); var_dump($content);
Although the file_get_contents()
function is very convenient to use, it is not flexible enough and cannot handle errors. In some complex requests, it is not possible to set request headers, cookies, proxies, authentication and other related information, let alone submit form data to a server or upload files.
The cURl library not only supports rich network protocols, but also provides methods for setting various URL request parameters, which is powerful. There are many usage scenarios for cURL, such as accessing web resources, obtaining WebService interface data, and downloading FTP server files.
To use cURL to send URL requests, the steps are roughly divided into the following four steps:
Initialization cURL session;
Set request options;
Execute cURL session;
Close cURL session .
// 1. 初始化 cURL 会话 $ch = curl_init(); // 2. 设置请求选项 curl_setopt($ch, CURLOPT_URL, "https://segmentfault.com"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); # 获取的信息以字符串返回,而不是直接输出 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); # 禁止 cURL 验证对等证书,从而支持 HTTPS 访问 // 3. 执行 cURL 会话 $response = curl_exec($ch); var_dump($response); // 4. 关闭 cURL 会话 curl_close($ch);
cURL mainly sets request options through the curl_setopt()
function. For detailed description of each option, please see http://php.net/manual/zh/ func...
You can view cURL session error details through the curl_error()
function, and the curl_getinfo()
function can view the response information. Therefore, through these two functions we can implement a simple error handler. For example, if we now access a non-existent URL address:
<?php // 1. 初始化 cURL 会话 $ch = curl_init(); // 2. 设置请求选项 curl_setopt($ch, CURLOPT_URL, "https://segmentfault.com/test.php"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); # 获取的信息以字符串返回,而不是直接输出 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); # 禁止 cURL 验证对等证书,从而支持 HTTPS 访问 // 3. 执行 cURL 会话 $response = curl_exec($ch); if ($response === FALSE) { echo "cURL connert error: " . curl_error($ch); exit; } $info = curl_getinfo($ch); if ($info['http_code'] == 404) { echo 'HTTP 404'; exit; } var_dump($response); // 4. 关闭 cURL 会话 curl_close($ch);
Use cURL to simulate sending a POST request:
<?php function curl_post($url, $data) { $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => 1, # 获取的信息以字符串返回 CURLOPT_POST => 1, # 发送 POST 请求 CURLOPT_POSTFIELDS => $data, # POST 请求数据 ]); $response = curl_exec($ch); curl_close($ch); return $response; } $url = 'http://localhost/test.php'; $data = ['id' => 1, 'username' => 'jochen']; echo curl_post($url, $data);
CURLOPT_POSTFIELDS: All data is sent using the "POST" operation in the HTTP protocol. To send a file, prefix the file name with @ and use the full path. The file type can be specified in the format ';type=mimetype' after the file name. This parameter can be a urlencoded string, similar to 'val1=1&val2=2&...', or you can use an array with the field name as the key and the field data as the value.
Send POST request through cURL to implement file upload:
<?php function curl_upload($url, $data) { $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => 1, # 获取的信息以字符串返回 CURLOPT_POST => 1, # 发送 POST 请求 CURLOPT_POSTFIELDS => $data, # POST 请求数据 ]); $response = curl_exec($ch); curl_close($ch); return $response; } $url = 'http://localhost/test.php'; $data = ['id' => 1, 'file' => '@/root/image/boy.jpg']; echo curl_post($url, $data);
In fact, file download is the same as ordinary GET request, except that file download returns The content is saved to a file rather than simply output. Cooperate with the file_put_contents()
function to implement file download:
56b62e99cd671c33a22cc122cd1dca25 $url, CURLOPT_RETURNTRANSFER => 1, # 获取的信息以字符串返回 ]); $response = curl_exec($ch); curl_close($ch); return file_put_contents($path, $response); } curl_download('http://localhost/boy.jpg', './boy.jpg');
If the server needs to verify the request, set the CURLOPT_USERPWD
parameter. :
<?php function curl_auth($url, $user, $passwd) { $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $url, CURLOPT_USERPWD => "$user:$passwd", # 格式为:"[username]:[password]" CURLOPT_RETURNTRANSFER => 1 ]); $result = curl_exec($ch); curl_close($ch); return $result; } echo curl_auth('http://localhost', 'jochen', 'password');
Here we mainly show applications that use cookies to maintain the login status. First we need to log in with the account and password to get the cookie data, and then use the logged in cookie to get the page data:
<?php // 模拟登录获取 Cookie function curl_login($url, $data, $cookie) { $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $url, CURLOPT_POST => 1, # 发送 POST 请求 CURLOPT_POSTFIELDS => $data, # POST 请求数据 CURLOPT_COOKIEJAR => $cookie # 将 cookie 信息保存至文件中 CURLOPT_RETURNTRANSFER => 1, # 获取的信息以字符串返回 ]); $response = curl_exec($ch); curl_close($ch); return $response; } // 获取页面数据 function curl_content($url, $cookie) { $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $url, CURLOPT_COOKIEFILE => $cookie # 加载包含 Cookie 数据的文件 CURLOPT_RETURNTRANSFER => 1, # 获取的信息以字符串返回 ]); $response = curl_exec($ch); curl_close($ch); return $response; } $post = ['username' => 'jochen', 'password' => '123456']; $cookie = './cookie.txt'; if (curl_login('http://localhost/login', $post, $cookie)) { echo curl_content('http://localhost', $cookie); }
PHP Curl Class is a well-written cURL package Library that makes it very easy to send HTTP requests and integrate with any kind of Web API. PHP Curl Class wrapper library is available for PHP 5.3, 5.4, 5.5, 5.6, 7.0, 7.1 and HHVM. This library is well known and provides a very simple syntax:
<?php require __DIR__ . '/vendor/autoload.php'; use \Curl\Curl; $curl = new Curl(); $curl->get('https://www.example.com/'); if ($curl->error) { echo 'Error: ' . $curl->errorCode . ': ' . $curl->errorMessage . "\n"; } else { echo 'Response:' . "\n"; var_dump($curl->response); }
Reference article:
Client URL Library
Introduction tutorial and common usage examples of curl in php
Using CURL in PHP, "teasing" the server only takes a few lines - php curl detailed analysis and common pitfalls
Top 7: Best Curl Wrapper Libraries for PHP
Related recommendations:
PHP Concurrency Use curl concurrency to reduce backend access time
PHP simulates login and obtains data through CURL
The above is the detailed content of cURL library in PHP. For more information, please follow other related articles on the PHP Chinese website!