How to find the number of lines in a text file in PHP

If you want to count the number of lines in a text file, you can get it using some simple PHP code. All you have to do is, open the file, read it line by line and use php string function fgets() with a counter. See the below code:


<?php
$fp = fopen("input.txt", "r") or die("Unable to open file!");
// count lines
$line_count = 0;
while (!feof($fp)) {   // loop until end of file
	$line = fgets($fp);
	++$line_count;
}
fclose($fp);
echo "No. of lines in the input file = ".$line_count;

In the above code, "input.txt" file is opened and $fp is the file pointer. It uses fgets() function in a loop and counts each line untill end of file is reached. Finally, it prints the counter.

Count number of lines in a text file in PHP

Let us see how we can write a simple PHP program to count the number of lines in a file and print the output in the browser. I have written a PHP program (index.php) to count the lines in a text file. This program is kept in a folder named 'line_count' under xampp/htdocs.

input.txt is the input text file, number of lines of which we are going to count. Below is content of the file:

Input text file (input.txt)


This is a test input file to count the number of lines in the file using PHP.
Using PHP open the file and count lines in a loop
Print the count after the loop as output
Close the input file

Count the number of lines in a text file (index.php)


<html>
<head>
	<title>Count lines in a file</title>
</head>
<body style="text-align: center;font-size: 20px;">
	<h1>Line count in a file</h1>
	<?php
	$fp = fopen("input.txt", "r") or die("Unable to open file!");
	// count lines
	$line_count = 0;
	while (!feof($fp)) {   // loop until end of file
		$line = fgets($fp);
		++$line_count;
	}
	fclose($fp);
	echo "No. of lines in the input file = ".$line_count;
	?>
</body>
</html>

It opens the file input.txt in read mode using fopen() PHP function. Using a while loop, it reads each line of the file using fgets() function and increments the counter. This is done till end of file is reached. After exiting from while loop, it closes the input file using fclose() function. At the end, it displays the count.

Let us now test it.

Keep "input.txt" in the same folder, i.e., in the folder xampp/htdocs. Run localhost/line_count in the browser. You will see the count displayed.

Number of lines in a text file in php example