This article mainly introduces eight methods and code examples for reading files in PHP. This article summarizes the eight functions for reading files in PHP, each with examples and precautions, for more information about how to read files in PHP, see.
1. fread
String fread (int $ handle, int $ length)
Fread () reads a maximum of length bytes from the file pointed to by handle. This function can be read by a maximum of length bytes, or when it reaches the EOF, or (for network streams) when a package is available, or (after opening the user space stream) when 8192 bytes have been read, the system stops reading files.
Fread () returns the read string. If an error occurs, FALSE is returned.
The code is as follows:
<? Php
$ Filename = "/usr/local/something.txt ";
$ Handle = fopen ($ filename, "r"); // when reading binary files, set the second parameter to 'RB'
// Obtain the file size through filesize and read the entire file to a string
$ Contents = fread ($ handle, filesize ($ filename ));
Fclose ($ handle );
?>
If the file to be read is not a local common file, but a remote file or stream file, this method cannot be used, because filesize cannot obtain the size of these files. In this case, you need to use the returned values of feof () or fread () to determine whether the object has been read to the end.
For example:
The code is as follows:
<? Php
$ Handle = fopen ('http: // www.baidu.com ', 'r ');
$ Content = '';
While (! Feof ($ handle )){
$ Content. = fread ($ handle, 8080 );
}
Echo $ content;
Fclose ($ handle );
?>
Or:
The code is as follows:
<? Php
$ Handle = fopen ('http: // www.baidu.com ', 'r ');
$ Content = '';
While (false! = ($ A = fread ($ handle, 8080) {// Return false to indicate that the object has been read to the end.
$ Content. = $;
}
Echo $ content;
Fclose ($ handle );
?>
2. fgets
String fgets (int $ handle [, int $ length])
Fgets () reads a row from the file pointed to by handle and returns a string with a maximum length-1 bytes. When a line break (including the returned value), EOF, or the length-1 byte is read, it is stopped ). If length is not specified, the default value is 1 K, or 1024 bytes.
The code is as follows:
<? Php
$ Handle = fopen ('./file.txt', 'r ');
While (! Feof ($ handle )){
Echo fgets ($ handle, 1024 );
}
Fclose ($ handle );
?>
Note: The length parameter is optional since PHP 4.2.0. If this parameter is ignored, the row length is assumed to be 1024. Starting from PHP 4.3, ignoring length will continue to read data from the stream until the row ends. If most of the rows in the file are larger than 8 kB, it is more effective to specify the length of the maximum row in the script to use resources. Starting from PHP 4.3, this function can be safely used for binary files. Earlier versions do not work.
3. fgetss
String fgetss (resource $ handle [, int $ length [, string $ allowable_tags])
Similar to the fgets function, fgetss will try to remove any HTML and PHP tags from the read text. you can use the optional third parameter to specify which tags will not be removed.
The code is as follows:
<? Php
$ Handle = fopen ('./file.txt', 'r ');
While (! Feof ($ handle )){
Echo fgetss ($ handle, 1024 ,'
');
}
Fclose ($ handle );
?>
4. file
Array file (string $ filename [, int $ use_include_path [, resource $ context])
Read the file content into an array. each item in the array corresponds to a row in the file, including a line break. You can use the rtrim () function to filter line breaks when no line terminator is required.
The code is as follows:
<? Php
$ A = file ('./file.txt ');
Foreach ($ a as $ line => $ content ){
Echo 'line'. ($ line + 1). ':'. $ content;
}
?>
5. readfile
Int readfile (string $ filename [, bool $ use_include_path [, resource $ context])
Read a file and write it to the output buffer. Returns the number of bytes read from the file. If an error is returned, FALSE is returned, and the error message is displayed unless called in the form of @ readfile.
The code is as follows:
<? Php
$ Size = readfile ('./file.txt ');
Echo $ size;
?>
6. file_get_contents
String file_get_contents (string $ filename [, bool $ use_include_path [, resource $ context [, int $ offset [, int $ maxlen])
Reads a file into a string. The third parameter $ context can be used to set some parameters, such as setting timeout when accessing a remote file.
In addition, compared with the above functions, file_get_contents has a much better performance. Therefore, file_get_contents should be preferred. But readfile seems to have better performance than file_get_contents (?), Because it does not need to call fopen.
The code is as follows:
<? Php
$ Ctx = stream_context_create (array (
'Http' => array (
'Timeout' => 1 // set timeout
)
)
);
Echo file_get_contents ("http://www.baidu.com/", 0, $ ctx );
?>
7. fpassthru
Int fpassthru (resource $ handle)
Read the given file pointer from the current location to EOF and write the result to the output buffer.
The code is as follows:
<? Php
Header ("Content-Type: text/html; charset = utf-8 ");
$ Handle = fopen ('./test2.php', 'r ');
Fseek ($ handle, 1024); // locate the pointer to 1024 bytes
Fpassthru ($ handle );
?>
8. parse_ini_file
Array parse_ini_file (string $ filename [, bool $ process_sections])
Parse_ini_file () loads an ini file specified by filename and returns the settings as a union array. If the final process_sections parameter is set to TRUE, a multidimensional array is obtained, including the name and settings of each section in the configuration file. The default value of process_sections is FALSE.
Note:
1. if the value in the ini file contains any non-alphanumeric characters, enclose it in double quotation marks (").
2. some reserved words cannot be used as the key names in the ini file, including: null, yes, no, true, and false. The values are null, no and false are equivalent to "", and yes and true are equivalent to "1 ". Character {} | &~! [() "Cannot be used anywhere in the key name, and these characters have special meanings in the option value.
Content of the test. ini file:
The code is as follows:
; This is a sample configuration file
; Comments start with ';', as in php. ini
[First_section]
One = 1
Five = 5
Animal = BIRD
[Second_section]
Path = "/usr/local/bin"
URL = "http://www.example.com /~ Username
Test. php content:
The code is as follows:
<? Php
$ Config = parse_ini_file ('./test. ini', ture );
Print_r ($ config );
?>
Output Content:
The code is as follows:
Array
(
[First_section] => Array
(
[One] => 1
[Five] => 5
[Animal] => BIRD
)
[Second_section] => Array
(
[Path] =>/usr/local/bin
[URL] => http://www.example.com /~ Username
)
)
Several notes:
1. encourage the use of the B flag when processing binary files, even if the system does not need it, this can make the script portability better.
2. the allow_url_fopen option activates the URL-based fopen encapsulation protocol to allow access to URL objects such as files. The default Encapsulation Protocol provides ftp and http protocols to access remote files. some extension libraries such as zlib may register more encapsulation protocols. For security reasons, this option can only be set in php. ini.
3. if you want to open a URL with special characters (such as spaces), you need to use urlencode () for URL encoding.