zoukankan      html  css  js  c++  java
  • PHP file_get_contents和curl区别

    一、file_get_contents

    1.定义

    file_get_contents() 函数将指定 URL 的文件读入一个字符串并返回。

    2.语法

    file_get_contents(path, include_path, context, start, max_length)
    
    • path:要读取的路径或链接。
    • include_path:是否在路径中搜索文件,搜索则设为 1,默认为 false。
    • context:修改流的行为,如超时时间,GET / POST 等。
    • start:开始读文件的位置。
    • max_length:读取文件的字节数。

    3.示例

    test.txt

    <?php
    echo "i'm a test php";
    ?>
    

    index.php

    <?php
    $testTxt = file_get_contents('./test.txt');
    var_dump($testTxt); // string(15) "i'm a test txt."
    
    $ctx = stream_context_create(
        array(
            'http' => array(
                'method' => 'get',
                'timeout' => 30
            )
        )
    );
    $testTxt = file_get_contents('./test.txt', false, $ctx, 4, 6);
    var_dump($testTxt); // string(6) "a test"
    ?>
    

    二、curl

    1.定义

    PHP 支持 Daniel Stenberg 创建的 libcurl 库,能够连接通讯各种服务器、使用各种协议。libcurl 目前支持的协议有 http、https、ftp、gopher、telnet、dict、file、ldap。 libcurl 同时支持 HTTPS 证书、HTTP POST、HTTP PUT、 FTP 上传(也能通过 PHP 的 FTP 扩展完成)、HTTP 基于表单的上传、代理、cookies、用户名+密码的认证。

    2.语法

    1. curl_init:初始化 cURL 会话。
    2. curl_setopt:设置 cURL 传输选项。
    3. curl_exec:返回 true / false,curl_setopt 设置 CURLOPT_RETURNTRANSFER 为 TRUE 时将 curl_exec() 获取的信息以字符串返回。
    4. curl_close:关闭 cURL 会话。

    3.示例

    test.php

    <?php
    echo "i'm a test php";
    ?>
    

    index.php

    <?php
    // 创建一个新 cURL 资源
    $ch = curl_init();
    
    // 设置URL和相应的选项
    curl_setopt($ch, CURLOPT_URL, "http://localhost/test.php"); // 需要获取的 URL 地址,也可以在 curl_init() 初始化会话的时候。
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
    curl_setopt($ch, CURLOPT_HEADER, false); // 启用时会将头文件的信息作为数据流输出。
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // 在尝试连接时等待的秒数。设置为 0,则无限等待。
    curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 允许 cURL 函数执行的最长秒数。
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // TRUE 将 curl_exec() 获取的信息以字符串返回,而不是直接输出。
    
    // 抓取 URL 并把它传递给浏览器
    $ret = curl_exec($ch);
    
    var_dump($ret);
    
    // 关闭 cURL 资源,并且释放系统资源
    curl_close($ch);
    ?>
    

    三、file_get_contents 和 curl 区别

    1.curl 支持更多功能

    curl 支持更多协议,有http、https、ftp、gopher、telnet、dict、file、ldap;模拟 Cookie 登录,爬取网页;FTP 上传下载。

    fopen / file_get_contents 只能使用 GET 方式获取数据。

    2.性能

    curl 可以进行 DNS 缓存,同一个域名下的图片或其它资源只需要进行一次DNS查询。

    curl 相对来说更加快速稳定,访问量高的时候首选 curl,缺点就是相对于 file_get_contents 配置繁琐一点,file_get_contents 适用与处理小访问的应用。

    PHP file_get_contents和curl区别

  • 相关阅读:
    通过Java获取图片的信息
    防止浏览器缓冲
    InitializingBean,DisposableBean
    php 直接跳出嵌套循环
    个推IGt.BaseTemplate.php,不仅有bug,还有bom头,好恶心!
    【洛谷】2473:[SCOI2008]奖励关【期望DP(倒推)】
    【BZOJ】4720: [Noip2016]换教室
    【BZOJ】4767: 两双手【组合数学】【容斥】【DP】
    【BZOJ】4318: OSU!【期望DP】
    【BZOJ】4985: 评分【DP】
  • 原文地址:https://www.cnblogs.com/mazey/p/8629289.html
Copyright © 2011-2022 走看看