php fread function introduction
string fread (int handle, int length)
fread() reads up to length bytes from the file pointer handle. This function is called after reading up to length bytes, or when EOF is reached, or (for network streams) when a packet is available, or (after opening a user space stream) 8192 bytes have been read. Reading of the file will stop.
fread() example:
<?php $file = "data.txt"; $fh = fopen($file, "rt"); $userdata = fread($fh, filesize($file)); fclose($fh); ?>
Some points you need to pay attention to when using fread in php
1. Solutions to errors when fread reads and writes large files
If the file exceeds php.ini when using fread to read a file When setting the maximum memory usage value in It is returned in the form of a string, so how does it identify the encoding method used in a.txt to ensure that it is not garbled?
Character encoding is not recognized in file operations for versions below PHP 7.0.
It is only output in byte data. If it is consistent with the character encoding of the php source code file and the output html, it can be displayed correctly.
3. When fread reads a file, there will always be an extra null character
<? set_time_limit(0);//设置脚本执行时间无限长 $flie="flexbuilder_linux_install_a5_112409.bin";//大文件超过php.ini中的内存配置 $fp=fopen($flie,"r"); $content=""; $filename="123.bin";//存为新文件 $handle=fopen($filename,"a");//写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之 while(!feof($fp)){//测试文件指针是否到了文件结束的位置 $content=fread($fp,1024); fwrite($handle,$content); } fclose($fp); fclose($handle); echo "数据成功写入文件"; ?>
When we use the above code to read the file, sometimes there will be an extra null character. This is because you are on a WINDOWS platform, and the file is a text file that is opened and stored. There will be a special byte at the end to mark the end of the file. If you open it with rb, you can naturally read the last special byte. Open it with r and read it with fgets.
I hope this article can help everyone, thank you for your support of this site!
For more articles related to the precautions for reading files with php fread, please pay attention to the PHP Chinese website!