当前位置:  首页>> 技术小册>> PHP合辑2-高级进阶

PHP中的fread()函数是一个内建函数,用于从一个打开的文件中读取文件指针file所引用的最多length个字节。fread()函数在到达文件的末尾或达到作为参数指定的长度时停止,以先发生者为准。要读取的文件和长度作为参数发送到fread()函数,它在成功时返回读取的字符串,或在失败时返回False。

语法:

  1. string fread ( file,length )

使用的参数:

PHP中的fread()函数接受两个参数。

file:它是一个必需的参数,用于指定文件。length:它是一个必需的参数,用于指定要读取的最大字节数。

返回值:它在成功时返回读取的字符串,或在失败时返回False。

例外:

像图像和字符数据这样的二进制数据都可以使用此函数写入,因为fread()是二进制安全的。
要将文件内容仅获取为字符串,请使用file_get_contents(),因为它的性能比上面的代码要好得多。
因为在Windows系统上区分二进制文件和文本文件,所以必须在fopen()模式参数中包含’b’来打开文件。
以下程序说明了fread()函数:

假设名为gfg.txt的文件包含以下内容:

  1. Goodsforgoods is a portal of goods!

示例1:

  1. <?php
  2. // Opening a file
  3. $myfile = fopen("gfg.txt", "r");
  4. // reading 13 bytes from the file
  5. // using fread() function
  6. echo fread($myfile, "13");
  7. // closing the file
  8. fclose($myfile);
  9. ?>

output:

  1. Goodsforgoods

示例2:

  1. <?php
  2. // Opening a file
  3. $myfile = fopen("gfg.txt", "r");
  4. // reading the entire file using
  5. // fread() function
  6. echo fread($myfile, filesize("gfg.txt"));
  7. // closing the file
  8. fclose($myfile);
  9. ?>

output:

  1. Goodsforgoods is a portal of goods!

示例3:

  1. <?php
  2. // Opening a file
  3. $myfile = "logo.jpg";
  4. // opening in binary read mode
  5. // for windows systems
  6. $myhandle = fopen($myfile, "rb");
  7. // reading an image using fread()
  8. echo fread($myhandle, filesize($myfile));
  9. // closing the file
  10. fclose($myhandle);
  11. ?>

output:

  1. 256

该分类下的相关小册推荐: