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
Overview
Introduction
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.
Advantages
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.
Usage
Basic steps
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...
Error handling
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);
Practical case
1. POST request
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);
2. File upload
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);
3. File download
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:
<?php function curl_download($url, $path) { $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $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');
4. HTTP authentication
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');
5. Simulated login
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); }
cURL package library
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!

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











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,

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.

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

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.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.
