Table of Contents
1. Introduction to cURL
2. cURL function library
4. Example 1: GET request
5. Example 2. POST request
6. Example 3. Upload files
7. Example 4. Download files
8. Example 5. Batch processing
Home Backend Development PHP Tutorial Detailed explanation of examples of cURL that is better than file_get_contents() in PHP

Detailed explanation of examples of cURL that is better than file_get_contents() in PHP

Sep 11, 2017 am 09:32 AM
curl file

PHP can use the file_get_content() function to crawl web page content, but it cannot perform more complex processing, such as file upload or download, cookie operations, etc. PHP's cURL provides these functions.

1. Introduction to cURL

cURL is an extension library for PHP. It can connect and communicate with various types of servers and using various types of protocols.

It currently supports http, https, ftp, gopher, telnet, dict, file and ldap protocols, and also supports HTTPS authentication, HTTP POST, FTP upload, proxy, cookies and username + password authentication, etc.

2. cURL function library

Commonly used functions

##FunctionDescription curl_init() Initialize cURL session curl_setopt() Settings cURL options curl_exec() Execute cURL session## curl_getinfo() curl_errno() curl_error() curl_close()

Get the current session information
Return the last error code
Return the last error string of the current session
Close the cURL session
Other functions


Functioncurl_copy_handle()curl_escape()curl_file_create()curl_multi_add_handle()curl_multi_close()curl_multi_exec()curl_multi_getcontent()curl_multi_info_read()curl_multi_init()curl_multi_remove_handle() curl_multi_select()curl_multi_setopt()curl_multi_strerror()curl_pause()curl_reset()curl_setopt_array()curl_share_close()curl_share_init()curl_share_setopt()curl_strerror()curl_unescape()curl_version()


3. Implementation process

1. Initialize cURL session

2. Set cURL options

3. Execute cURL session

4 . Get cURL information and/or error information (this step is optional)

5. Close the cURL handle

The most complicated part here is step 2. There are many cURL setting options. Below we will learn about it with examples.


4. Example 1: GET request

 The process of GET request is the general process of cURL.

Prepare a test script index.php in the root directory of the local server localserver.com. The content is as follows:

<?php
    $url = &#39;http://www.baidu.com&#39;;
    // 初始化,获得一个cURL句柄
    $ch = curl_init();
    
    // 设置选项
    curl_setopt($ch, CURLOPT_URL, $url); // 请求URL
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回数据流,而不直接输出
    curl_setopt($ch, CURLOPT_HEADER, 0); // 无需响应的header头
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); //连接超时,秒为单位

    // 执行并获取返回内容
    $output = curl_exec($ch);
    if($output === false){
        $output = &#39;cURL error: &#39; . curl_error($ch);
    }
    // 释放 cURL 句柄资源
    curl_close($ch);

    print_r($output);
?>
Copy after login

The browser accesses the local server homepage localserver.com/index.php and displays the Baidu homepage.

5. Example 2. POST request

POST request needs to set two options:

curl_setopt($ch, CURLOPT_POST, 1); // 表明POST请求
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData)); // POST提交数据
Copy after login

First prepare a script for receiving in the root directory of the remote server remoteserver.com index.php, the content is as follows:

<?php
    $input = file_get_contents(&#39;php://input&#39;);
    echo $input;
?>
Copy after login

Then write the script index.php for POST request in the root directory of the local server localserver.com, the content is as follows:

<?php
    $url = &#39;http://remoteserver.com/index.php&#39;;
    $data = array(
        &#39;fname&#39;=> &#39;Daniel&#39;,
        &#39;lname&#39; => &#39;Stenberg&#39;
    );

     // 初始化
    $ch = curl_init();
    
    // 设置选项
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_POST, 1); // POST请求
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); //POST数据。用http_build_query()转换为“&”拼接的字符串

    // 执行并获取返回内容
    $output = curl_exec($ch);
    if($output === false){
        $output =  &#39;cURL error: &#39; . curl_error($ch);
    }

    // 释放 cURL 句柄资源
    curl_close($ch);

    print_r($output);
?>
Copy after login

The browser accesses localserver. com/index.php, displayed as follows:

fname=Daniel&lname=Stenberg
Copy after login

6. Example 3. Upload files

The idea of ​​cURL uploading files is: add the "@" symbol in front of the file path and install it in Upload is implemented in the request field. The background can obtain uploaded file information through $_FILES. However, after PHP5.6, the "@" symbol is abolished, and the CURLFile class can be used to implement uploading.

First prepare a script index.php for receiving in the root directory of the remote server remoteserver.com, with the following content:

<?php
    $action = $_POST[&#39;action&#39;];
    if($action == &#39;uploadImage&#39;){
        $name = $_FILES[&#39;file&#39;][&#39;name&#39;];
        $tmpname = $_FILES[&#39;file&#39;][&#39;tmp_name&#39;];
        
        // 保存到当前脚本所在目录
        move_uploaded_file($tmpname, dirname(__FILE__).&#39;/&#39;.$name);

        $error = $_FILES[&#39;file&#39;][&#39;error&#39;];
        switch ($error) {
            case 0: echo &#39;上传成功&#39;; break;
            case 1: echo &#39;文件大小超出 php.ini 限制&#39;; break;
            case 2: echo &#39;文件大小超出 表单 MAX_FILE_SIZE 限制&#39;; break;
            case 3: echo &#39;文件部分被上传&#39;; break;
            case 4: echo &#39;没有文件被上传&#39;; break;
            case 6: echo &#39;找不到临时文件夹&#39;; break;
            case 7: echo &#39;文件写入失败&#39;; break;
            default: $output = &#39;未知错误&#39;;
        }
    }
?>
Copy after login

Then prepare an image file test in the root directory of the local server localserver.com .jpg and cURL upload script index.php, the script content is as follows:

<?php
    $url = &#39;http://remoteserver.com/index.php&#39;;
    $file = realpath(getcwd() . &#39;/test.jpg&#39;);
    $data = array(
        &#39;action&#39; => &#39;uploadImage&#39;,
        &#39;file&#39; => &#39;@&#39; . $file
    );
    if(version_compare(PHP_VERSION, &#39;5.6.0&#39;) > 0){
        $data[&#39;file&#39;] = new CURLFile($file);
    }
    
    // 初始化
    $ch = curl_init();
    
    // 设置选项
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    // 执行并获取返回内容
    $output = curl_exec($ch);
    if($output === false){
        $output =  &#39;cURL error: &#39; . curl_error($ch);
    }

    // 释放 cURL 句柄资源
    curl_close($ch);

    print_r($output);
?>
Copy after login

When the browser accesses localserver.com/index.php, the display is as follows:

上传成功
Copy after login

Check the root directory of the remote server and find many A picture I just uploaded.

7. Example 4. Download files

One idea for downloading files using cURL is to set the cURL option CURLOPT_FILE as a file pointer to associate the requested resource file with a file stream. This file stream is generally the return value of the fopen() function. Using file streams to write remote files locally can avoid possible memory errors when writing (downloading) large files.

Write the test script index.php in the root directory of the local server localserver.com. The content is as follows:

<?php
    $url = &#39;http://remoteserver.com/test.jpg&#39;;
    $file = &#39;./test.jpg&#39;;
    $fp = fopen($file, &#39;w&#39;);

    // 初始化
    $ch = curl_init();

    // 设置选项
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_FILE, $fp); // 用于传输的文件流,默认是STDOUT

    // 执行并获取返回内容
    $output = curl_exec($ch);
    if($output === false){
        $output =  &#39;cURL error: &#39; . curl_error($ch);
    }

    // 获取已下载大小
    $size_download = curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD);

    // 释放资源
    fclose($fp);
    curl_close($ch); 

    if ($size_download && $size_download == filesize($file)) {
        echo "下载成功";
    } else {
        echo "下载失败或不完整";
    }   
?>
Copy after login

When the browser accesses localserver.com/index.php, the display is as follows:

下载成功
Copy after login

Check the root directory of the local server and find that the remote image has been downloaded.

8. Example 5. Batch processing

cURL has a batch handle. By opening multiple cURL handles, binding these handles to a batch handle, and then sequentially in the loop Processing each cURL connection can achieve asynchronous batch processing, similar to "multi-threading".

Write the test script index.php in the root directory of the local server localserver.com. The content is as follows:

<?php
    $urls = array(
        &#39;http://www.baidu.com&#39;,
        &#39;http://www.qidian.com&#39;
    );
    $count = count($urls);
    $ch = array();

    // 创建批处理cURL句柄
    $mh = curl_multi_init();

    // 初始化每个cURL,并设置选项,绑定给批处理句柄
    for ($i = 0; $i < $count; $i++) {
        $ch[$i] = curl_init();
        curl_setopt($ch[$i], CURLOPT_URL, $urls[$i]);
        curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch[$i], CURLOPT_HEADER, 0);
        curl_setopt($ch[$i], CURLOPT_CONNECTTIMEOUT, 30);
        curl_multi_add_handle($mh, $ch[$i]);
    }

    // 执行批处理
    $running = null;
    do {
        usleep(10000); // 延迟0.01秒,单位为百万分之一秒
        curl_multi_exec($mh, $running); // 异步实现批处理,类似“多线程”
    } while($running > 0);

    // 获取每个cURL的响应
    $res = array();
    for ($i = 0; $i < $count; $i++) {
        $res[$i] = curl_multi_getcontent($ch[$i]);
    }

    // 关闭全部句柄
    for ($i = 0; $i < $count; $i++) {
        curl_multi_remove_handle($mh, $ch[$i]);
    }
    curl_multi_close($mh);

    print_r($res);
?>
Copy after login

The browser accesses localserver.com/index.php and displays the "Connected" Baidu homepage. and Qidian.com homepage.

Description
Copy A cURL handle and all its options.
Returns the escape string, URL encoding the given string.
Create a CURLFile object.
Add individual curl handles to a cURL batch session.
Close a group of cURL handles.
Runs a sub-connection of the current cURL handle.
If CURLOPT_RETURNTRANSFER is set, returns the text stream of the obtained output.
Get the relevant transmission information of the currently parsed cURL.
Returns a new cURL batch handle.
Remove a handle resource in the cURL batch handle resource.
Wait for all active connections in a cURL batch.
Set a batch cURL transfer option.
Returns a string text describing the error code.
Pause and resume the connection.
Reset all options of libcurl's session handle.
Set options for cURL transfer sessions in bulk.
Close the cURL shared handle.
Initialize the cURL share handle.
Sets the cURL transfer options for a shared handle.
Returns a string description of the error code.
Decode the URL-encoded string.
Get cURL version information.

The above is the detailed content of Detailed explanation of examples of cURL that is better than file_get_contents() 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)

How to realize the mutual conversion between CURL and python requests in python How to realize the mutual conversion between CURL and python requests in python May 03, 2023 pm 12:49 PM

Both curl and Pythonrequests are powerful tools for sending HTTP requests. While curl is a command-line tool that allows you to send requests directly from the terminal, Python's requests library provides a more programmatic way to send requests from Python code. The basic syntax for converting curl to Pythonrequestscurl command is as follows: curl[OPTIONS]URL When converting curl command to Python request, we need to convert the options and URL into Python code. Here is an example curlPOST command: curl-XPOST https://example.com/api

Use java's File.length() function to get the size of the file Use java's File.length() function to get the size of the file Jul 24, 2023 am 08:36 AM

Use Java's File.length() function to get the size of a file. File size is a very common requirement when dealing with file operations. Java provides a very convenient way to get the size of a file, that is, using the length() method of the File class. . This article will introduce how to use this method to get the size of a file and give corresponding code examples. First, we need to create a File object to represent the file we want to get the size of. Here is how to create a File object: Filef

Hongmeng native application random poetry Hongmeng native application random poetry Feb 19, 2024 pm 01:36 PM

To learn more about open source, please visit: 51CTO Hongmeng Developer Community https://ost.51cto.com Running environment DAYU200:4.0.10.16SDK: 4.0.10.15IDE: 4.0.600 1. To create an application, click File- >newFile->CreateProgect. Select template: [OpenHarmony] EmptyAbility: Fill in the project name, shici, application package name com.nut.shici, and application storage location XXX (no Chinese, special characters, or spaces). CompileSDK10, Model: Stage. Device

Tutorial on updating curl version under Linux! Tutorial on updating curl version under Linux! Mar 07, 2024 am 08:30 AM

To update the curl version under Linux, you can follow the steps below: Check the current curl version: First, you need to determine the curl version installed in the current system. Open a terminal and execute the following command: curl --version This command will display the current curl version information. Confirm available curl version: Before updating curl, you need to confirm the latest version available. You can visit curl's official website (curl.haxx.se) or related software sources to find the latest version of curl. Download the curl source code: Using curl or a browser, download the source code file for the curl version of your choice (usually .tar.gz or .tar.bz2

How to convert php blob to file How to convert php blob to file Mar 16, 2023 am 10:47 AM

How to convert php blob to file: 1. Create a php sample file; 2. Through "function blobToFile(blob) {return new File([blob], 'screenshot.png', { type: 'image/jpeg' })} ” method can be used to convert Blob to File.

From start to finish: How to use php extension cURL to make HTTP requests From start to finish: How to use php extension cURL to make HTTP requests Jul 29, 2023 pm 05:07 PM

From start to finish: How to use php extension cURL for HTTP requests Introduction: In web development, it is often necessary to communicate with third-party APIs or other remote servers. Using cURL to make HTTP requests is a common and powerful way. This article will introduce how to use PHP to extend cURL to perform HTTP requests, and provide some practical code examples. 1. Preparation First, make sure that php has the cURL extension installed. You can execute php-m|grepcurl on the command line to check

PHP8.1 released: Introducing curl for concurrent processing of multiple requests PHP8.1 released: Introducing curl for concurrent processing of multiple requests Jul 08, 2023 pm 09:13 PM

PHP8.1 released: Introducing curl for concurrent processing of multiple requests. Recently, PHP officially released the latest version of PHP8.1, which introduced an important feature: curl for concurrent processing of multiple requests. This new feature provides developers with a more efficient and flexible way to handle multiple HTTP requests, greatly improving performance and user experience. In previous versions, handling multiple requests often required creating multiple curl resources and using loops to send and receive data respectively. Although this method can achieve the purpose

Rename files using java's File.renameTo() function Rename files using java's File.renameTo() function Jul 25, 2023 pm 03:45 PM

Use Java's File.renameTo() function to rename files. In Java programming, we often need to rename files. Java provides the File class to handle file operations, and its renameTo() function can easily rename files. This article will introduce how to use Java's File.renameTo() function to rename files and provide corresponding code examples. The File.renameTo() function is a method of the File class.

See all articles