大网数据广告活动
PHP 语言与运行手册

fread · 读取文件(可安全用于二进制文件)

· 52CE 我爱测

fread() 从文件指针 stream 读取最多 length 个字节。 该函数在遇上以下几种情况时停止读取文件: 读取了 length 个字节

fread

(PHP 4, PHP 5, PHP 7, PHP 8)

fread — 读取文件(可安全用于二进制文件)

说明

function fread(resource $stream, int $length): string|false

fread() 从文件指针 stream 读取最多 length 个字节。 该函数在遇上以下几种情况时停止读取文件:

  • 读取了 length 个字节

  • 到达了文件末尾(EOF)

  • a packet becomes available or the socket timeout occurs (for network streams)

  • if the stream is read buffered and it does not represent a plain file, at most one read of up to a number of bytes equal to the chunk size (usually 8192) is made; depending on the previously buffered data, the size of the returned data may be larger than the chunk size.

参数

stream

文件系统指针,是典型地由 fopen() 创建的 resource(资源)。

length

最多读取 length 个字节。

返回值

返回所读取的字符串, 或者在失败时返回 false。

示例

示例 #1 一个简单的 fread() 例子

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

示例 #2 Binary fread() example

警告

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

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

示例 #3 Remote fread() examples

警告

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

<?php
$handle = fopen("http://www.example.com/", "rb");
if (FALSE === $handle) {
    exit("Failed to open stream to URL");
}

$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(),它的性能比上面的代码好得多。

注意:

Note that fread() reads from the current position of the file pointer. Use ftell() to find the current position of the pointer and rewind() to rewind the pointer position.

参见

  • fwrite() - 写入文件(可安全用于二进制文件)
  • fopen() - 打开文件或者 URL
  • fsockopen() - 打开 Internet 或者 Unix 套接字连接
  • popen() - 打开进程文件指针
  • fgets() - 从文件指针中读取一行
  • fgetss() - 从文件指针中读取一行并过滤掉 HTML 标记
  • fscanf() - 从文件中格式化输入
  • file() - 把整个文件读入一个数组中
  • fpassthru() - 输出文件指针处的所有剩余数据
  • fseek() - 在文件指针中定位
  • ftell() - 返回文件指针读/写的位置
  • rewind() - 倒回文件指针的位置
  • unpack() - Unpack data from binary string

来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
PHP Documentation Group
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。