search
HomeBackend DevelopmentPHP TutorialDetailed explanation of examples of cURL that is better than file_get_contents() in PHP

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);
?>

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提交数据

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;
?>

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);
?>

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

fname=Daniel&lname=Stenberg

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;;
        }
    }
?>

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);
?>

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

上传成功

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 "下载失败或不完整";
    }   
?>

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

下载成功

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);
?>

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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)