一、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

  1. <?php

  2. echo "i'm a test php";

  3. ?>

index.php

  1. <?php

  2. $testTxt = file_get_contents('./test.txt');

  3. var_dump($testTxt); // string(15) "i'm a test txt."

  4.  
  5. $ctx = stream_context_create(

  6. array(

  7. 'http' => array(

  8. 'method' => 'get',

  9. 'timeout' => 30

  10. )

  11. )

  12. );

  13. $testTxt = file_get_contents('./test.txt', false, $ctx, 4, 6);

  14. var_dump($testTxt); // string(6) "a test"

  15. ?>

二、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

  1. <?php

  2. echo "i'm a test php";

  3. ?>

index.php

  1. <?php

  2. // 创建一个新 cURL 资源

  3. $ch = curl_init();

  4.  
  5. // 设置URL和相应的选项

  6. curl_setopt($ch, CURLOPT_URL, "http://localhost/test.php"); // 需要获取的 URL 地址,也可以在 curl_init() 初始化会话的时候。

  7. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');

  8. curl_setopt($ch, CURLOPT_HEADER, false); // 启用时会将头文件的信息作为数据流输出。

  9. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // 在尝试连接时等待的秒数。设置为 0,则无限等待。

  10. curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 允许 cURL 函数执行的最长秒数。

  11. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // TRUE 将 curl_exec() 获取的信息以字符串返回,而不是直接输出。

  12.  
  13. // 抓取 URL 并把它传递给浏览器

  14. $ret = curl_exec($ch);

  15.  
  16. var_dump($ret);

  17.  
  18. // 关闭 cURL 资源,并且释放系统资源

  19. curl_close($ch);

  20. ?>

三、file_get_contents 和 curl 区别

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

1.fopen /file_get_contents 每次请求都会重新做DNS查询,并不对 DNS信息进行缓存。但是CURL会自动对DNS信息进行缓存。对同一域名下的网页或者图片的请求只需要一次DNS查询。这大大减少了DNS查询的次数。所以CURL的性能比fopen /file_get_contents 好很多。

2.curl 可以模拟多种请求,例如:POST数据,表单提交等,用户可以按照自己的需求来定制请求。而fopen / file_get_contents只能使用get方式获取数据。
file_get_contents 获取远程文件时会把结果都存在一个字符串中 fiels函数则会储存成数组形式

3.fopen /file_get_contents 在请求HTTP时,使用的是http_fopen_wrapper,不会keeplive。而curl却可以。这样在多次请求多个链接时,curl效率会好一些。

4.fopen / file_get_contents 函数会受到php.ini文件中allow_url_open选项配置的影响。如果该配置关闭了,则该函数也就失效了。而curl不受该配置的影响。

 

因此,我还是比较倾向于使用curl来访问远程url。Php有curl模块扩展,功能很是强大。

 

 

 

eg: 调用第三方微信接口 (获取素材id)

public function save_data($params) {
    $this->load->library('weixin_client');
    $wechat = $this->weixin_client::getInstance($params['app_id']);
    if (empty($wechat)) {
        $this->api_result->set_api_error(-1, '请完善公众号配置信息!', '请完善公众号配置信息!');
        return;
    }

    $this->load->config('upload');
    $config = $this->config->item('upload');
    $path = $config['upload_path'] . $params['data']['file_name'];
    $media_id = $wechat->add_material_long($path, $params['type']);
    if (empty($media_id)) {
        $this->api_result->set_api_error(-1, '素材media_id获取失败!', '素材media_id获取失败!');
        return;
    }
}
public function add_material_long($local_media_file, $type) {
    $url = "https://api.weixin.qq/cgi-bin/material/add_material?" . 'access_token=' . $this->accessToken . "&type=" . $type;

    $ch = curl_init();
    $post_data = array(
        'media' => new \CURLFile(realpath($local_media_file))
    );

    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    $response = curl_exec($ch);


    if (curl_errno($ch)) {
        $this->print_error('add_material_long, curl_errno=' . curl_error($ch));
        curl_close($ch);
        return FALSE;
    }

    if ($response) {
        $this->print_debug('add_material_long, response=' . $response);
        $ret_arr = json_decode($response, TRUE);
        curl_close($ch);

        //"errcode\":40001,\"errmsg\":\"invalid credential, access_token is invalid or not latest
        if (isset($ret_arr["errcode"]) && $ret_arr["errcode"] == 40001) {
            //refresh the cached token
            $this->getAccessToken(TRUE);
            //return $this->upload_img_long($local_media_file);
            return false;
        }

        if (!isset($ret_arr["media_id"])) {
            return FALSE;
        }
        return $ret_arr;
    }

    curl_close($ch);
    return FALSE;
}

 

 

更多推荐

php 调用第三方接口