How to read last n lines from a file in PHP


Here we will see how to read last n lines from a file in PHP, where n could be replaced by any positive integer number, such as, 1, 2, 5, 10 etc. Generally most of the times we use to read the file in forward direction, i.e., from the beginning of the file and apply some business processing logic on file data according to the application’s requirements. But sometimes you need to read a file in backward direction, i.e., from the end of the file and you may need to extract last few lines from a file for your application’s need. Then you can use one of the solutions from below code snippets.

You may also like to read how to read last n lines from a file using Java.


Knowledge of PHP

Let’s move on to the code implementation of how to read last n lines from a file in PHP…

Example with Code

Your file may be a small, medium or big depending on your project’s requirements and here I will present with two different solutions you can use according to your need.

Solution – One

When you need to extract last few lines from a small file then you can use below solution.


	$file = file("Terms and Conditions 2012_FRL.txt");
	$readLines = max(0, count($file)-n); //n being non-zero positive integer

	if($readLines > 0) {
		for ($i = $readLines; $i < count($file); $i++) {
			echo $file[$i];
			echo nl2br("n");
	} else {
		echo 'file does not have required no. of lines to read';


The above solution will consume much memory, so if your file is small then only use the above solution.

Solution – Two

This solution will work for your small as well as very big file. We will use here SplFileObject to reduce the memory cost. Use the seek() method to fetch the last line. You should then subtract the current key value by n, where n being the non-zero positive integer.


	$file = new SplFileObject('Terms and Conditions 2012_FRL.txt', 'r');
	$last_line = $file->key();
	$lines = new LimitIterator($file, $last_line - n, $last_line); //n being non-zero positive integer

Note that SplFileObject class has a private property that holds the file pointer. Therefore, there is no method to close the file handle, and you get into situations where you are not able to delete the file with unlink() method, because an SplFileObject still has a handle open. Then you have to do some workaround in the following way to delete the file.

$file = new SplFileObject("filename.txt");
$file = null; //explicitly assign null
unlink($file); //now delete the file

That’s all. Hope you got idea how to read last n lines from a file in PHP.

Thanks for reading.

How to read last n lines from a file in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top