PHP中的fread()函数是一个内建函数,用于从一个打开的文件中读取文件指针file所引用的最多length个字节。fread()函数在到达文件的末尾或达到作为参数指定的长度时停止,以先发生者为准。要读取的文件和长度作为参数发送到fread()函数,它在成功时返回读取的字符串,或在失败时返回False。
语法:
string fread ( file,length )
使用的参数:
PHP中的fread()函数接受两个参数。
file:它是一个必需的参数,用于指定文件。length:它是一个必需的参数,用于指定要读取的最大字节数。
返回值:它在成功时返回读取的字符串,或在失败时返回False。
例外:
像图像和字符数据这样的二进制数据都可以使用此函数写入,因为fread()是二进制安全的。
要将文件内容仅获取为字符串,请使用file_get_contents(),因为它的性能比上面的代码要好得多。
因为在Windows系统上区分二进制文件和文本文件,所以必须在fopen()模式参数中包含’b’来打开文件。
以下程序说明了fread()函数:
假设名为gfg.txt的文件包含以下内容:
Goodsforgoods is a portal of goods!
示例1:
<?php
// Opening a file
$myfile = fopen("gfg.txt", "r");
// reading 13 bytes from the file
// using fread() function
echo fread($myfile, "13");
// closing the file
fclose($myfile);
?>
output:
Goodsforgoods
示例2:
<?php
// Opening a file
$myfile = fopen("gfg.txt", "r");
// reading the entire file using
// fread() function
echo fread($myfile, filesize("gfg.txt"));
// closing the file
fclose($myfile);
?>
output:
Goodsforgoods is a portal of goods!
示例3:
<?php
// Opening a file
$myfile = "logo.jpg";
// opening in binary read mode
// for windows systems
$myhandle = fopen($myfile, "rb");
// reading an image using fread()
echo fread($myhandle, filesize($myfile));
// closing the file
fclose($myhandle);
?>
output:
256