Introduction to PHP fread functions
string fread (int handle, int length)
Fread () reads up to length bytes from a file pointer handle. The function stops reading a file when it has read up to a maximum length of bytes, or when it reaches EOF, or (for a network stream) when a package is available, or when 8,192 bytes have been read (after the user space stream is opened).
Fread () Example:
<?php $file = "Data.txt"; $fh = fopen ($file, "RT"); $userdata = Fread ($fh, FileSize ($file)); Fclose ($FH);? >
Some points to be aware of when using PHP fread
1, Fread read write to large file error resolution
The following method resolves the problem of reading large files if the maximum memory usage value set in php.ini is exceeded when using fread to read the file:
<? Set_time_limit (0);//Set Script execution time is infinite $flie = "flexbuilder_linux_install_a5_112409.bin";//large file exceeds memory configuration in php.ini $ Fp=fopen ($flie, "R"); $content = ""; $filename = "123.bin";//Save as new file $handle =fopen ($filename, "a");//write open to point the file pointer to the end of the file. If the file does not exist, try to create the while (!feof ($fp)) {//test file pointer to the location where the file ends $content =fread ($fp, 1024x768); Fwrite ($handle, $content); } Fclose ($FP); Fclose ($handle); echo "Data successfully written to file";? >
2, PHP fread () is how to identify the file encoding
<?php$handler=fopen (' a.txt ', ' RB ')//Binary mode open $content=fread ($handler, 1024x768); Echo $content;? >
Fread is returned as a string, how does it recognize the encoding used by a.txt, to ensure that it is not garbled?
The character encoding is not recognized in the file operation of the following version of PHP7.0.
Just by byte data output, if and the PHP source code file and output HTML character encoding consistent can be displayed correctly.
3, Fread read the file will always be more than one empty character
$fileSize = FileSize ($filePath), $handle = fopen ($filePath, "RB"), while (!feof ($handle)) { var_dump (fread ($handle), $fileSize)); Will output one more empty character}
When we use the above code to read the file, sometimes there will be more than one empty character. This is because you are the Windows platform, the file is the text to open the stored content, at the end there will be a special byte to identify the end of the file, you can use the RB open nature will be able to read the last special byte. Open with R, Fgets read it.
Through this article hope to help everyone, thank you for the support of this site!