FlamingGenius
FlamingGenius

Reputation: 216

Effecient way to read a file php

Currently I am using this to open a file and read its contents line by line

<?php
    $scriptText = "";

    $file_handle = fopen("TestScript.cs","r");
    while(!feof($file_handle)){
        $line = fgets($file_handle);
        $scriptText = $scriptText . $line;
    }
    fclose($file_handle);

    $size = strlen($scriptText);

    header('Content-type: text/html');
    header("Content-length: $size");

    echo $scriptText;
?>

For a file < 1mb this is acceptable but lets say we have a file 40mb this is just way to slow

Is there a faster way of doing this?

EDIT:

To clarify efficient I dont want execution time surpassing the 30sec timeout limit. I could increase the execution time but I would much prefer to cut the time down instead of allocation more time.

Also I am not using a shared hosting provider it is a cloud server I am running using apache/xampp and if I can solve the issue through upgrading my servers power I can do that

Upvotes: 0

Views: 66

Answers (2)

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21681

@Sean Denny answer is probably the most efficient way if all you need to do is send the file to output.

But if you need to access the file line by line, say you have to filter or modify the data from the file for some reason. You can still improve on the original questions code.

$size = filesize();

//open output buffer
$output_handle = fopen('php://output', 'w');

$file_handle = fopen("TestScript.cs","r");

header('Content-type: text/html');
header("Content-length: $size");

while(!feof($file_handle)){
    $line = fgets($file_handle);
    $line = strtolower($line);  //modify line, for examples sake
    fwrite($output_handle, $line);
}

You can use php://output to write to the output buffer directly. This cuts down the amount of memory you are using because each line is read, modified, spit out to the output buffer and not stored in PHP.

However you still have to itterate though the file, so readfile is better in your case. I just wanted to give an example on how to improve outputting if you still need access to the line data of the file for some reason.

For example, I've used it to output CSV data where I had to check for certain column data to remove a given row(s) from the download. (it was around 250MB of data too) except I used fgetcsv for the reading, but that's pretty much irrelevant to the "how" of outputting it.

Upvotes: 2

Meghan
Meghan

Reputation: 1261

Use readfile() to read a file's contents directly to the output buffer

<?php
$file = "TestScript.cs";
header('Content-Length: '.filesize($file));
readfile($file);
?>

Upvotes: 3

Related Questions