Php code for reading large files-PHP source code

Source: Internet
Author: User
In php, it is very easy to read common small files, but it may require some tips if we want to use php to read large files, below I will summarize how php reads large file instances. in php, it is very easy to read common small files, but it may require some tips if we want to use php to read large files, below I will summarize how php reads large file instances.

Script ec (2); script

In php development, you often encounter reading some files. The easiest way is to use functions such as file and file_get_contents. A few simple lines of code can be easily done. However, when the file to be operated 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.

Requirement: there is a more than 5 million MB log file with about lines. Use php to return the last few lines of content.

The implementation methods are as follows:

1. directly use the file function.

Note: 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.

The Code is as follows:

Ini_set ('memory _ limit ','-1 ');
$ File = 'access. log ';
$ Data = file ($ file );
$ Line = $ data [count ($ data)-1];
Echo $ line;

The execution of the entire Code takes 116.9613 (s ).

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 ten thousand. memory_limit cannot be too high. Otherwise, you only need to call the data center and 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.

The Code is as follows:

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:

The Code is as follows:

$ 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 Line Operators (n.

The implementation code is as follows:

The Code is as follows:

$ 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;

The execution of the entire Code takes 0.0009 (s ).

Method 3:

The Code is as follows:

Function 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)

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.