关于php fread()使用技巧

yipeiwu_com5年前PHP代码库
说明
string fread ( int handle, int length )
fread() 从文件指针 handle 读取最多 length 个字节。该函数在读取完最多 length 个字节数,或到达 EOF 的时候,或(对于网络流)当一个包可用时,或(在打开用户空间流之后)已读取了 8192 个字节时就会停止读取文件,视乎先碰到哪种情况。
返回所读取的字符串,如果出错返回 FALSE。
复制代码 代码如下:

<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize ($filename));
fclose($handle);
?>

警告
在区分二进制文件和文本文件的系统上(如 Windows)打开文件时,fopen() 函数的 mode 参数要加上 'b'。
复制代码 代码如下:

<?php
$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize ($filename));
fclose($handle);
?>

警告
当从任何不是普通本地文件读取时,例如在读取从远程文件或 popen() 以及 proc_open() 返回的流时,读取会在一个包可用之后停止。这意味着应该如下例所示将数据收集起来合并成大块。
复制代码 代码如下:

<?php
// 对 PHP 5 及更高版本
$handle = fopen("http://www.example.com/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
?>

<?php
$handle = fopen ("http://www.example.com/", "rb");
$contents = "";
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
?>

注意: 如果只是想将一个文件的内容读入到一个字符串中,用 file_get_contents(),它的性能比上面的代码好得多。
额外:
file_get_contents
(PHP 4 >= 4.3.0, PHP 5)
file_get_contents -- 将整个文件读入一个字符串
说明
string file_get_contents ( string filename [, bool use_include_path [, resource context [, int offset [, int maxlen]]]] )

和 file() 一样,只除了 file_get_contents() 把文件读入一个字符串。将在参数 offset 所指定的位置开始读取长度为 maxlen 的内容。如果失败,file_get_contents() 将返回 FALSE。
file_get_contents() 函数是用来将文件的内容读入到一个字符串中的首选方法。如果操作系统支持还会使用内存映射技术来增强性能。

相关文章

PHP 获取ip地址代码汇总

代码一: function getip() { static $ip = ''; $ip = $_SERVER['REMOTE_ADDR']; if(isset($_SE...

php Xdebug 调试扩展的安装与使用.

Xdebug安装 下载xdebug扩展的时候注意xdebug的版本与php版本相对应,不然出现不必要的麻烦! 我自己使用的是PHP5.2.5,下载的xdebug文件名为:php_xdeb...

基于PHP CURL用法的深入分析

如下所示:复制代码 代码如下:<?phpheader('Context-Type:text/html;charset:gb2312;');$urls = array( '...

PHP实现变色验证码实例

复制代码 代码如下: <?php header("Content-type: image/png,charset='utf-8'"); $im = imagecreatetruec...

php下使用curl模拟用户登陆的代码

bool curl_setopt (int ch, string option, mixed value) curl_setopt()函数将为一个CURL会话设置选项。option参数是...