PHP fread()函数用法介绍

2021年3月11日18:15:12 发表评论 856 次浏览

fread()PHP中的function是一个内置函数, 该函数从打开的文件中引用的文件指针中读取最大长度的字节。的fread()函数停止在文件末尾或达到指定长度(作为参数传递)时(以先到者为准)。文件和必须读取的长度作为参数发送到fread()函数, 如果成功则返回读取的字符串, 如果失败则返回FALSE。

语法如下:

string fread ( $file, $length )

使用的参数:

fread()

PHP中的function接受两个参数。

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

返回值:

  • 如果成功, 则返回读取的字符串;如果失败, 则返回False。

例外情况:

  • 二进制图像, 例如图像和字符数据, 都可以使用此功能写入, 因为fread()是二进制安全的。
  • 要将文件内容仅转换为字符串, 请使用file_get_contents()因为它比上面的代码具有更好的性能。
  • 由于运行Windows的系统区分二进制文件和文本文件, 因此必须在文件中使用" b"打开文件fopen()模式参数。

下面的程序说明了fread()功能:

假设一个名为gfg.txt包含以下内容:

lsbin是极客的门户!

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

输出如下:

lsbin

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

输出如下:

lsbin is a portal of geeks!

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

输出如下:

256

参考:

http://php.net/manual/en/function.fread.php


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: