PHP (short for Hypertext Preprocessor) is a widely-used open-source server-side scripting language designed for web development and can be embedded into HTML. It has a syntax similar to C, is easy to learn, and supports numerous databases like MySQL, PostgreSQL, and SQLite. PHP is ideal for building dynamic web pages and applications.
When working with files such as logs or data records, there are several approaches in PHP to efficiently read the last line. Below are three practical solutions.
The file() function reads the entire file into an array, where each element represents a line from the file:
$lines = file('example.txt');
You can retrieve the last line using end($lines). However, this method loads the entire file into memory, which is not optimal for large files.
For larger files, a more memory-efficient way is to use fseek() and fgets() to move the file pointer near the end and read from there:
$file = 'example.txt';
$fp = fopen($file, 'r');
if (!$fp) {
exit("Can't open file: $file");
}
fseek($fp, -1, SEEK_END);
$newline = fgetc($fp);
if ($newline !== "\n") {
fseek($fp, -1, SEEK_CUR);
}
while (($char = fgetc($fp)) !== false && $char !== "\n") {
fseek($fp, -2, SEEK_CUR);
}
$lastLine = fgets($fp);
fclose($fp);
This method is ideal for performance-sensitive environments and allows precise control over the file pointer, especially when the file doesn't end with a newline character.
PHP’s SplFileObject from the Standard PHP Library provides a simpler and more elegant solution for reading the last line:
$file = 'example.txt';
$fileObj = new SplFileObject($file);
$fileObj->seek(PHP_INT_MAX);
$lastLine = $fileObj->current();
$fileObj = null;
This approach avoids the complexity of manually managing file pointers and is both clean and efficient.
Depending on file size and performance requirements, developers can choose from the following options to read the last line of a file in PHP:
Mastering these methods will improve your efficiency when working with file operations in PHP, such as log parsing or configuration management.