Current Location: Home> Latest Articles> PHP Tips: How to Store Filename in a Variable and Count Lines in a File

PHP Tips: How to Store Filename in a Variable and Count Lines in a File

gitbox 2025-06-27

Common Methods to Store Filename in a Variable in PHP

PHP is a widely used web development language that not only handles web content but also provides convenient file operations. Here are some common methods to store a filename in a variable using PHP.

Using readfile() Function to Read File and Store Filename

The readfile() function reads the content of a file and outputs it, while the filename can be stored in a variable. Example code:

$filename = "example.txt";
$content = readfile($filename);

Using fopen() and fclose() Functions to Handle File Name Variable

The fopen() function opens a file, and fclose() closes it. These functions can be used together to operate on a file and store its name in a variable. Example:

$filename = "example.txt";
$file = fopen($filename, "r");
fclose($file);

Methods to Count the Number of Lines in a File with PHP

Counting the number of lines in a file is a common task. PHP offers several ways to achieve this. Here are two frequently used methods.

Using file() Function to Read File and Count Lines

The file() function reads the entire file into an array, with each element representing one line. Using count() on the array returns the number of lines. Example code:

$filename = "example.txt";
$file = file($filename);
$lines = count($file);

Using fgets() Function to Read File Line by Line and Count Lines

The fgets() function reads a file line by line inside a loop, allowing you to count all lines. Example code:

$filename = "example.txt";
$file = fopen($filename, "r");
$lines = 0;
while (!feof($file)) {
    $line = fgets($file);
    $lines++;
}
fclose($file);

Conclusion

This article explained how to store a filename in a variable in PHP and count the number of lines in a file using various methods. Depending on your needs, you can choose to use readfile(), fopen()/fclose(), file(), or fgets() to efficiently perform file reading and line counting tasks.