user1346598
user1346598

Reputation: 233

Pause-Continue reading large text file with php

I have the below PHP code. I want to be able to continue reading the text file from the point it stopped, and the text file is over 90mb.

Is it possible to continue reading from the point the script stopped running?

$in = fopen('email.txt','r');

while($kw = trim(fgets($in))) {
    //my code
}

Upvotes: 0

Views: 429

Answers (1)

ThiefMaster
ThiefMaster

Reputation: 318488

No, that's not easily possible without saving the current state from time to time.

However, instead of doing that you should better try to fix whatever causes your script to stop. set_time_limit(0); and ignore_user_abort(true); will most likely prevent your script from being stopped while it's running.

If you do want to be able to continue from some position, use ftell($in) to get the position and store it in a file/database from time to time. When starting the script you check if you have a stored position and then simply fseek($in, $offset); after opening the file.

If the script is executed from a browser and it takes enough time to make aborts likely, you could also consider splitting it in chunks and cleanly terminating the script with a redirect containing an argument where to continue. So your script would process e.g. 1000 lines and then be restarted with an offset of 1000 to process the next 1000 lines and so on.

Upvotes: 1

Related Questions