What are some alternative methods to readfile() for handling files larger than 2MB in PHP?

When working with files larger than 2MB in PHP, using the readfile() function may not be the most efficient option as it loads the entire file into memory, potentially causing memory issues. To handle large files more efficiently, you can use alternative methods such as fopen(), fread(), and fclose() to read the file in chunks and process it incrementally.

$filePath = 'path/to/large/file.txt';

$handle = fopen($filePath, 'r');
if ($handle) {
    while (!feof($handle)) {
        $chunk = fread($handle, 1024); // Read 1KB at a time
        // Process the chunk (e.g., echo it, save to another file, etc.)
    }
    fclose($handle);
}