Table of Contents
Overview
Introduction
Advantages
Usage
Basic steps
Error handling
Practical case
1. POST request
2. File upload
3. File download
4. HTTP authentication
5. Simulated login
cURL package library
Home Backend Development PHP Tutorial cURL library in PHP

cURL library in PHP

Apr 09, 2018 pm 03:51 PM
curl 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);
Copy after login

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:

  1. Initialization cURL session;

  2. Set request options;

  3. Execute cURL session;

  4. 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);
Copy after login
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[&#39;http_code&#39;] == 404) {
    echo &#39;HTTP 404&#39;;
    exit;
}

var_dump($response);

// 4. 关闭 cURL 会话
curl_close($ch);
Copy after login

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  = &#39;http://localhost/test.php&#39;;
$data = [&#39;id&#39; => 1, &#39;username&#39; => &#39;jochen&#39;];
echo curl_post($url, $data);
Copy after login

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  = &#39;http://localhost/test.php&#39;;
$data = [&#39;id&#39; => 1, &#39;file&#39; => &#39;@/root/image/boy.jpg&#39;];
echo curl_post($url, $data);
Copy after login

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(&#39;http://localhost/boy.jpg&#39;, &#39;./boy.jpg&#39;);
Copy after login

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(&#39;http://localhost&#39;, &#39;jochen&#39;, &#39;password&#39;);
Copy after login

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 = [&#39;username&#39; => &#39;jochen&#39;, &#39;password&#39; => &#39;123456&#39;];
$cookie = &#39;./cookie.txt&#39;;
if (curl_login(&#39;http://localhost/login&#39;, $post,  $cookie)) {
    echo curl_content(&#39;http://localhost&#39;, $cookie);
}
Copy after login

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__ . &#39;/vendor/autoload.php&#39;;

use \Curl\Curl;

$curl = new Curl();
$curl->get(&#39;https://www.example.com/&#39;);

if ($curl->error) {
    echo &#39;Error: &#39; . $curl->errorCode . &#39;: &#39; . $curl->errorMessage . "\n";
} else {
    echo &#39;Response:&#39; . "\n";
    var_dump($curl->response);
}
Copy after login

Reference article:

  1. Client URL Library

  2. Introduction tutorial and common usage examples of curl in php

  3. Using CURL in PHP, "teasing" the server only takes a few lines - php curl detailed analysis and common pitfalls

  4. 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!

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

Video Face Swap

Video Face Swap

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

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

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

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

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: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

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 in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

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: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

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

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

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.

See all articles