Use fopen() with fgets() or fread() to read large files in chunks, avoiding memory exhaustion. Process line by line for text files or use binary buffers for better control. SplFileObject offers a clean, object-oriented alternative. Always stream data instead of loading it entirely into memory.
Reading a large file in PHP efficiently means avoiding high memory usage and slow performance. Loading the entire file into memory with functions like file_get_contents() can cause memory exhaustion. Instead, process the file in chunks using a loop that reads one line or segment at a time.
Use fopen() and fgets() for line-by-line reading
If your large file is structured in lines (like logs or CSV), read it one line at a time:
$handle = fopen("large_file.txt", "r"); if ($handle) { while (($line = fgets($handle)) !== false) { // Process each line echo $line; } fclose($handle); } else { // Error opening file }
This method uses minimal memory because only one line is loaded at a time.
Read in binary chunks with fread()
For non-text files or when you need more control over the read size, use fread() with a fixed buffer size:
$handle = fopen("large_file.bin", "rb"); $bufferSize = 8192; // 8KB per read while (!feof($handle)) { $chunk = fread($handle, $bufferSize); if ($chunk === false) break; // Process chunk echo $chunk; } fclose($handle);
Adjust the buffer size based on your system and performance needs. This approach works well for binary or very large text files.
Consider SplFileObject for object-oriented control
PHP’s SplFileObject provides an object-oriented interface and built-in iteration:
$file = new SplFileObject("large_file.txt"); while (!$file->eof()) { $line = $file->fgets(); // Process line echo $line; }
It's cleaner and supports iteration via foreach, and handles edge cases better than raw functions.
Efficient file reading in PHP comes down to streaming instead of loading all at once. Use fgets() for line-based data, fread() for binary or custom buffering, and consider SplFileObject for cleaner code. Keep memory usage low by never storing the whole file unless absolutely necessary.
Basically just avoid file_get_contents() and file() on big files — they load everything into RAM. Stick to iterative reading, and you’ll handle multi-gigabyte files smoothly.
The above is the detailed content of How to read a large file efficiently in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Usefilter_var()tovalidateemailsyntaxandcheckdnsrr()toverifydomainMXrecords.Example:$email="user@example.com";if(filter_var($email,FILTER_VALIDATE_EMAIL)&&checkdnsrr(explode('@',$email)[1],'MX')){echo"Validanddeliverableemail&qu

Useunserialize(serialize($obj))fordeepcopyingwhenalldataisserializable;otherwise,implement__clone()tomanuallyduplicatenestedobjectsandavoidsharedreferences.

Usearray_merge()tocombinearrays,overwritingduplicatestringkeysandreindexingnumerickeys;forsimplerconcatenation,especiallyinPHP5.6 ,usethesplatoperator[...$array1,...$array2].

NamespacesinPHPorganizecodeandpreventnamingconflictsbygroupingclasses,interfaces,functions,andconstantsunderaspecificname.2.Defineanamespaceusingthenamespacekeywordatthetopofafile,followedbythenamespacename,suchasApp\Controllers.3.Usetheusekeywordtoi

ToupdateadatabaserecordinPHP,firstconnectusingPDOorMySQLi,thenusepreparedstatementstoexecuteasecureSQLUPDATEquery.Example:$pdo=newPDO("mysql:host=localhost;dbname=your_database",$username,$password);$sql="UPDATEusersSETemail=:emailWHER

The__call()methodistriggeredwhenaninaccessibleorundefinedmethodiscalledonanobject,allowingcustomhandlingbyacceptingthemethodnameandarguments,asshownwhencallingundefinedmethodslikesayHello().2.The__get()methodisinvokedwhenaccessinginaccessibleornon-ex

Use the ZipArchive class to create a ZIP file. First instantiate and open the target zip, add files with addFile, support custom internal paths, recursive functions can package the entire directory, and finally call close to save to ensure that PHP has write permissions.

Usepathinfo($filename,PATHINFO_EXTENSION)togetthefileextension;itreliablyhandlesmultipledotsandedgecases,returningtheextension(e.g.,"pdf")oranemptystringifnoneexists.
