Home > Article > Backend Development > How to use fread() to read files in PHP
This article mainly introduces how to use PHP’s built-in fread() function in PHP to obtain the number of bytes when confirming and not confirming the acquisition. Number of bytes, in both cases, the method used to read the file contents.
1.fread syntax:
fread ( resource $handle , int $length ) : string
$handle: file system Pointer, usually a resource created by fopen().
$length: Read the byte length of the file.
Return value: A string of $length length.
2. Read the file (confirm the bytes that need to be read):
exit.txt file
php.cn good better
php file
<?php //文件路径 $filename="./exit.txt"; //获取文件资源 $file = fopen($filename,'r'); //读取二进制文件时,需要将第二个参数设置成'rb' //获取文件内容 $file_info=fread($file,10); //打印文件内容 echo $file_info; //关闭文件资源 fclose($file); ?>
输出结果:php.cn goo
3. Read the file (do not confirm the bytes to be read):
If you need to get all the contents of the file, you need to use another function filesize() function, which is specially used to check the size of the file
<?php //文件路径 $filename="./exit.txt"; //获取文件资源 $file = fopen($filename,'r'); //获取文件大小 $file_size= filesize($filename); //获取文件内容 $file_info=fread($file, $file_size); //打印文件内容 echo $file_info; //关闭文件资源 fclose($file); ?>
输出结果:php.cn good better
Recommendation: 《2021 Summary of annual PHP interview questions (collection)》《php video tutorial》
The above is the detailed content of How to use fread() to read files in PHP. For more information, please follow other related articles on the PHP Chinese website!