Multiple methods for reading large files in PHP are introduced,

Source: Internet
Author: User

Multiple methods for reading large files in PHP are introduced,

Reading large files has always been a headache. We can use various functions to read small files using php, however, as soon as the article is published, we will find that the common method is that it cannot be used normally or the time is too long and too slow. Let's take a look at the solution to the problem of reading large files in php, I hope the examples can help you.

In PHP, the quickest way to read files is to use functions such as file and file_get_contents, A few simple lines of code can perfectly complete the functions we need. However, when the operated file is a relatively large file, these functions may not be able to work properly. The following describes how to read large files from a requirement, common operation methods.

Requirements:
There is a more than 5 million MB log file with about lines. Use PHP to return the last few lines of content.

Implementation Method:

1. directly use the file function.
The file function reads all the content into the memory at a time. To prevent some poorly written programs from occupying too much memory, PHP causes insufficient system memory and server downtime, therefore, the maximum memory usage is 16 MB by default. set memory_limit = 16 M in ini. If this value is set to-1, the memory usage is not limited.

Below is a piece of code that uses file to retrieve the last line of the file:

<?php  ini_set('memory_limit', '-1');  $file = 'access.log';  $data = file($file);  $line = $data[count($data) - 1];  echo $line;?>

It takes 116.9613 seconds to complete the code execution ).
My machine has 2 GB of memory. When I press F5 to run the machine, the system will be grayed out directly, and it will be restored after about 20 minutes. It can be seen that all such large files will be directly read into the memory, the consequence is serious, so no more than. memory_limit cannot be too high. Otherwise, you only need to call the data center to let the reset machine go.

2. directly call the Linux tail command to display the last few lines
In the Linux Command Line, you can directly use tail-n 10 access. log to easily display the last few lines of the log file. You can directly use PHP to call the tail command and execute the PHP Code as follows:

<? Php $ file = 'access. log'; $ file = escapeshellarg ($ file); // escape command line parameters safely $ line = 'Tail-n 1 $ file'; echo $ line;?>

It takes 0.0034 seconds to complete the code execution)

3. directly use PHP fseek for file operations
This method is the most common method. It does not need to read all the content of the file, but directly uses pointers for operations, so the efficiency is quite efficient. When using fseek to operate files, there are also a variety of different methods, and the efficiency may be slightly different. Below are two common methods:

Method 1
First, find the last EOF the file through fseek, then find the starting position of the last row, get the data of this row, find the starting position of the next row, and then take the location of this row, and so on until the $ num row is found.
The implementation code is as follows:

<?php$fp = fopen($file, "r");$line = 10;$pos = -2;$t = " ";$data = "";while ($line > 0){ while ($t != "\n") { fseek($fp, $pos, SEEK_END); $t = fgetc($fp); $pos--; } $t = " "; $data .= fgets($fp); $line--;}fclose($fp);echo $data?>

It takes 0.0095 seconds to complete the code execution)

Method 2
The fseek method is used to read the last part of the file, but it is not a one-bit read, but a one-piece read. When each piece of data is read, put the read data in a buf, and then determine whether the last $ num row data has been read by changing the number of linefeeds (\ n.
The implementation code is as follows:

<?php$fp = fopen($file, "r");$num = 10;$chunk = 4096;$fs = sprintf("%u", filesize($file));$max = (intval($fs) == PHP_INT_MAX) ? PHP_INT_MAX : filesize($file);for ($len = 0; $len < $max; $len += $chunk){ $seekSize = ($max - $len > $chunk) ? $chunk : $max - $len; fseek($fp, ($len + $seekSize) * -1, SEEK_END); $readData = fread($fp, $seekSize) . $readData; if (substr_count($readData, "\n") >= $num + 1) { preg_match("!(.*?\n){" . ($num) . "}$!", $readData, $match); $data = $match[0]; break; }}fclose($fp);echo $data;?>

It takes 0.0009 seconds to complete the code execution ).

Method 3

<?phpfunction tail($fp, $n, $base = 5){ assert($n > 0); $pos = $n + 1; $lines = array(); while (count($lines) <= $n) { try {  fseek($fp, -$pos, SEEK_END); } catch (Exception $e) {  fseek(0);  break; } $pos *= $base; while (!feof($fp)) {  array_unshift($lines, fgets($fp)); } } return array_slice($lines, 0, $n);}var_dump(tail(fopen("access.log", "r+"), 10));?>

It takes 0.0003 seconds to complete the code execution)

Method 4: PHP's stream_get_line function reads data quickly. It takes about 20 seconds to read 0.5 million large data files! The sample code is as follows:

$ Fp = fopen ('./iis. log', 'R'); // file while (! Feof ($ fp) {// for ($ j = 1; $ j <= 1000; $ j ++) {// read the following 1000 rows and store them in the array $ logarray [] = stream_get_line ($ fp, 65535, "\ n"); // break ;//}}

The above are four methods for php to read large files. I hope this will be helpful for your learning.

Articles you may be interested in:
  • The correct method for PHP to read files
  • PHP reads the File Content Code (txt, js, etc)
  • Php file garbled characters
  • Php reads the content of the file to a string, while removing line breaks, blank lines, and spaces at the beginning and end of the line (original Zjmainstay)
  • PHP reads files and supports code sharing of remote files
  • Several Methods for php to Read File Content
  • Php code used to read the file header and determine the file type
  • PHP clears the sample code after reading the File Content
  • PHP three methods to delete line breaks when reading files by line
  • Php Method for reading the file content to an array

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.