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

黄舟
Release: 2023-03-15 21:42:01
Original
2564 people have browsed it

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!

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