8 ways to read files in PHP and code instance _php instance

Source: Internet
Author: User
Tags fread php and readfile alphanumeric characters

I have sorted out several methods of reading files in PHP, which is convenient to consult later.

1.fread

string fread (int $handle, int $length)

Fread () reads up to length bytes from the file pointed to by handle. The function stops reading a file when it reads up to a maximum length of bytes, or when it reaches EOF, or (for a network stream) when a package is available, or (after opening a user-space stream), reads 8,192 bytes, depending on which situation you first encounter.

Fread () returns the Read string, FALSE If an error is returned.

Copy Code code as follows:

<?php
$filename = "/usr/local/something.txt";
$handle = fopen ($filename, "R");//When reading a binary file, you need to set the second parameter to ' RB '

Get the file size by filesize, and read the entire file into a string
$contents = Fread ($handle, FileSize ($filename));
Fclose ($handle);
?>

This method cannot be used if the file being read is not a local normal file, but rather a remote file or stream file, because FileSize cannot get the size of the files. At this point, you need to determine whether you have read the end of the file by feof () or by the return value of Fread ().
  
For example:

Copy Code code as follows:

<?php
$handle = fopen (' http://www.baidu.com ', ' R ');
$content = ';
while (!feof ($handle)) {
$content. = Fread ($handle, 8080);
}
Echo $content;
Fclose ($handle);
?>

Or:

Copy Code code as follows:

<?php
$handle = fopen (' http://www.baidu.com ', ' R ');
$content = ';
while (false!= ($a = fread ($handle, 8080)) {//return false means read to end of file
$content. = $a;
}
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 of length-1 bytes. Stops when a line break is encountered (including in the return value), EOF, or after the length-1 byte has been read (see what happens first). If length is not specified, the default is 1 K, or 1024 bytes.

Copy Code code as follows:

<?php
$handle = fopen ('./file.txt ', ' R ');
while (!feof ($handle)) {
Echo fgets ($handle, 1024);
}
Fclose ($handle);
?>

The note:length parameter is optional from PHP 4.2.0, and if omitted, the length of the row is assumed to be 1024. starting with PHP 4.3, ignoring length will continue to read data from the stream until the line ends. If most of the rows in the file are greater than 8KB, specifying the length of the maximum row in the script is more efficient at leveraging resources. Starting with PHP 4.3 This function can be safely used in binary files. Earlier versions were not.

3.fgetss

String Fgetss (Resource $handle [, int $length [, String $allowable _tags]])

Like the fgets feature, but FGETSS will try to remove any HTML and PHP tags from the read text, and you can specify which tags are not removed with the optional third argument.

Copy Code code as follows:

<?php
$handle = fopen ('./file.txt ', ' R ');
while (!feof ($handle)) {
Echo fgetss ($handle, 1024, ' <br> ');
}
Fclose ($handle);
?>

4.file

Array file (string $filename [, int $use _include_path [, Resource $context]])

Reads the contents of the file into an array, each of which corresponds to a row in the file, including line breaks. You can use the RTrim () function to filter newline characters when you do not need a line terminator.

Copy Code code 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]])

Reads a file and writes it to the output buffer. Returns the number of bytes read from the file. If the error returns false and an error message is displayed unless invoked in the form of @readfile ().

Copy Code code 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 the file into a string. The third parameter, $context, can be used to set some parameters, such as when accessing remote files, setting timeouts, and so on.

In addition, file_get_contents is much better than several of the above functions, so the use of file_get_contents should be given priority. But ReadFile looks better than file_get_contents performance. Because it does not need to invoke fopen.

Copy Code code 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)

Reads the given file pointer from the current location to EOF and writes the result to the output buffer.

Copy Code code as follows:

<?php
Header ("Content-type:text/html;charset=utf-8");
$handle = fopen ('./test2.php ', ' R ');
Fseek ($handle, 1024);//Position the pointer at 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 its settings as a federated array. If you set the last process_sections argument to TRUE, you will get a multidimensional array that includes the name and settings for each section in the configuration file. The default value for Process_sections is FALSE.

Attention:
1. If the value in the INI file contains any non-alphanumeric characters, you need to enclose it in double quotes (").
2. Some reserved words cannot be used as key names in the INI file, including: Null,yes,no,true and false. A value of Null,no and false is equivalent to "", and a value of Yes and true is equivalent to "1". Character {}|&~! [() Nor can it be used anywhere in the key name, and these characters have special meaning in the value of the option.
Test.ini File Contents:

Copy Code code 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:

Copy Code code as follows:
<?php
$config = Parse_ini_file ('./test.ini ', ture);
Print_r ($config);
?>

Output content:

Copy Code code 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
)

)

A few things to note:

1. Encourage the use of the B flag when processing binaries, even if the system does not need to, so that the script can be better ported.

2. The allow_url_fopen option activates the URL-form fopen encapsulation protocol that allows access to URL objects such as files. The default encapsulation protocol provides FTP and HTTP protocols to access remote files, and some extensions, 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 a special character (for example, a space), you need to use UrlEncode () to encode the URL.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.