![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Read last line from file in PHP
To read last line from file in PHP, the code is as follows −
$line = ''; $f = fopen('data.txt', 'r'); $cursor = -1; fseek($f, $cursor, SEEK_END); $char = fgetc($f); //Trim trailing newline characters in the file while ($char === "
" || $char === "\r") { fseek($f, $cursor--, SEEK_END); $char = fgetc($f); } //Read until the next line of the file begins or the first newline char while ($char !== false && $char !== "
" && $char !== "\r") { //Prepend the new character $line = $char . $line; fseek($f, $cursor--, SEEK_END); $char = fgetc($f); } echo $line;
Output will be the last line of the text file will be read and displayed.
The text file is opened in read mode, and the cursor is set to point to -1, i.e. nothing initially. The ‘fseek’ function is used to move to the end of the file or the last line. The line is read until a newline is encountered. After this, the read characters are displayed.
Advertisements