cURL library in PHP

不言
Release: 2023-03-23 11:50:02
Original
1842 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template