SoFunction
Updated on 2025-03-10

Summary of several methods of reading files in PHP (recommended)

string fread ( int $handle , int $length )

fread() reads up to length bytes from the file pointed to by handle. This function stops reading the file when the maximum length bytes is read, or when the EOF is reached, or when (for network streams) a packet is available, or when 8192 bytes have been read (after opening the user space stream), depending on which situation is encountered first.

fread() returns the read string, and if there is an error, it returns FALSE.

<?php
  $filename = "/usr/local/";
  $handle = fopen($filename, "r");//When reading a binary file, you need to set the second parameter to 'rb'  
  //Get file size through filesize and read the entire file into a string at once  $contents = fread($handle, filesize ($filename));
  fclose($handle);
?>

If the file you want to read is not a local normal file, but a remote file or a stream file, you cannot use this method because filesize cannot obtain the size of these files. At this time, you need to use the return value of feof() or fread() to determine whether the end of the file has been read.

For example:

<?php
  $handle = fopen('', 'r');
  $content = '';
  while(!feof($handle)){
    $content .= fread($handle, 8080);
  }
  echo $content;
  fclose($handle);
?>

or:

&lt;?php
  $handle = fopen('', 'r');
  $content = '';
  while(false != ($a = fread($handle, 8080))){//Return false to indicate that it has been read to the end of the file    $content .= $a;
  }
  echo $content;
  fclose($handle);
?&gt;

string fgets ( int $handle [, int $length ] )

fgets() reads a line from the file pointed to by handle and returns a string of length up to length - 1 byte. It stops after encountering a newline character (including in the return value), EOF, or length - 1 byte has been read (see which case you encounter first). If length is not specified, the default is 1K, or 1024 bytes.

<?php
  $handle = fopen('./', 'r');
  while(!feof($handle)){
    echo fgets($handle, 1024);
  }
  fclose($handle);
?>

Note: length parameter becomes optional since PHP 4.2.0, and if ignored, the length of the line is assumed to be 1024. Starting with PHP 4.3, ignoring length will continue to read data from the stream until the end of the row. If most lines in the file are larger than 8KB, specifying the maximum length of the line in the script is more efficient in utilizing resources. Starting with PHP 4.3, this function is safe to use in binary files. The earlier versions did not work.

string fgetss ( resource $handle [, int $length [, string $allowable_tags ]] )

Like the fgets function, but fgetss tries to remove any HTML and PHP tags from the read text, and can use the optional third parameter to specify which tags are not removed.

<?php
  $handle = fopen('./', 'r');
  while(!feof($handle)){
    echo fgetss($handle, 1024, '<br>');
  }
  fclose($handle);
?>

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 line in the file, including line breaks. When no line endings are required, you can use the rtrim() function to filter newlines.

<?php
  $a = file('./');
  foreach($a as $line => $content){
    echo 'line '.($line + 1).':'.$content;
  }
?>

int readfile ( string $filename [, bool $use_include_path [, resource $context ]] )

Read in a file and write to the output buffer. Returns the number of bytes read from the file. If an error returns FALSE and an error message is displayed unless it is called in @readfile().

<?php
  $size = readfile('./');
  echo $size;
?>

6.file_get_contents

string file_get_contents ( string $filename [, bool $use_include_path [, resource $context [, int $offset [, int $maxlen ]]]] )

Read the file into a string. The third parameter $context can be used to set some parameters, such as setting timeout when accessing remote files, etc.

In addition, file_get_contents has much better performance than the above functions, so file_get_contents should be preferred. But readfile seems to perform a little better than file_get_contents (?) because it does not require calling fopen.

&lt;?php 
  $ctx = stream_context_create(array( 
    'http' =&gt; array( 
      'timeout' =&gt; 1  //Set timeout      ) 
    ) 
  ); 
  echo file_get_contents("/", 0, $ctx); 
?&gt;

int fpassthru ( resource $handle )

Read the given file pointer to EOF from the current location and write the result to the output buffer.

&lt;?php 
  header("Content-Type:text/html;charset=utf-8"); 
  $handle = fopen('./', 'r');
  fseek($handle, 1024);//Position the pointer to 1024 bytes  fpassthru($handle);
?&gt;

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 in it as a union array. If the last process_sections parameter is set to TRUE, a multi-dimensional array will be obtained, including the name and settings of each section in the configuration file. The default value of process_sections is FALSE.

Notice:

1. If the value in the ini file contains any non-alphanumeric characters, it needs to be enclosed in double quotes (").

2. Some reserved words cannot be used as key names in ini files, including: null, yes, no, true, and false. The values ​​are null, no and false are equivalent to "", and the values ​​are yes and true are equivalent to "1". The characters {}|&~![()" cannot be used anywhere in the key name, and these characters have special meanings in option values.

File content:

; This is a sample configuration file
; Comments start with ';', as in 

[first_section]
one = 1
five = 5
animal = BIRD

[second_section]
path = "/usr/local/bin"
URL = "/~username

content:

<?php 
  $config = parse_ini_file('./', ture);
  print_r($config);
?>

Output content:

Array
(
  [first_section] => Array
    (
      [one] => 1
      [five] => 5
      [animal] => BIRD
    )

  [second_section] => Array
    (
      [path] => /usr/local/bin
      [URL] => /~username
    )

)

A few things to note:

1. It is encouraged to use the b flag when processing binary files, even if the system does not require it, which can make the script more portable.

2. The allow_url_fopen option activates the fopen encapsulation protocol in the form of URLs so that URL objects such as files can be accessed. The default encapsulation protocol provides access to remote files using the ftp and http protocols, and some extension libraries such as zlib may register more encapsulation protocols. For security reasons, this option can only be set in .

3. If you want to open a URL with special characters (for example, there are spaces), you need to use urlencode() for URL encoding.

The above summary of several methods of reading files in PHP (recommended) is all the content I share with you. I hope you can give you a reference and I hope you can support me more.