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:

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 program to count number of lines in a file and print the output in the browser. I have written php code to count lines in index.php and kept them in a folder named 'line_count' under xampp/htdocs. See below:

get the number of lines in a file using PHP

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)

PHP code to count number of lines in a text file (index.php)

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.

PHP script to count lines in a text fileTest the Application

Make sure in your XAMPP control panel Apache is running. Open the browser and run localhost/line_count. You will see the page opened with count displayed.

Number of lines in a text file in php example