Introduction to the implementation method of reading a 1G file size in PHP

黄舟
Release: 2023-03-16 09:10:01
Original
1125 people have browsed it

[Background]: Since the file function reads all the contents into the memory at one time, and PHP needs to prevent some poorly written programs from taking up too much memory and causing insufficient system memory and causing the server to crash. Think of something better.

[Ideas]:


01 思路1:利用php执行linux的命令,将一个文件内容(a.log)复制到另一个文件中(b.log)
cat a.log >>b.log02 思路2:用php执行linux的head命令,获取内容,一行行写入另一个文件(b.log)中。
cat a.log|wc -l
sed -n '1 p' a.logfileputcontents('b.log’, $content, FILE_APPEND);
Copy after login

[Code Implementation]:

//02.读取1G的文件内容
 public function testGetLarge()
 {/*{{{*/
     #01. 方法1 直接cat后重定向
     #if('useCat' == 'useCat')
     if(0 && 'useCat' == 'useCat')
     {
         `cat a.log>>b.log`;
     }

     #02. 使用flie_put_contents ,一行一行读取并追加写入
     if('useFilePutContents' == 'useFilePutContents')
     {/*{{{*/
         $lineNum = `cat a.log|wc -l`;
         for($i=1; $i<= $lineNum; $i++)
         {
             $content = `sed -n &#39;$i p&#39; a.log`;
             //文件追加
             file_put_contents(&#39;b.log&#39;, $content, FILE_APPEND);
         }

     }/*}}}*/
Copy after login

The above is the detailed content of Introduction to the implementation method of reading a 1G file size in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template