0

I'm trying to open a file and determine if it is valid. It's valid if the first line is START and the last line is END.

I've seen different ways of getting the last line of a file, but it does not pay particular attention to the first line either.

How should I go about this? I was thinking of loading the file contents in an array and checking $array[0] and $array[x] for START and END. But this seems to be a waste for all the junk that could possibly be in the middle.

If its a valid file, I will be reading/processing the contents of the file between START and END.

Mike
  • 419
  • 1
  • 5
  • 14
  • 1
    use `fgets` to read the first line. for the last line see http://stackoverflow.com/questions/15025875/what-is-the-best-way-in-php-to-read-last-lines-from-a-file/15025877#15025877 – FuzzyTree Dec 07 '14 at 20:48
  • Maybe useful: [6451232/reading-large-files-from-end](https://stackoverflow.com/questions/6451232/reading-large-files-from-end). Also see [File seek: See the examples for accessing files quickly from the end](http://php.net/manual/en/function.fseek.php). – Ryan Vincent Dec 07 '14 at 21:11

3 Answers3

1

Don't read entire file into an array if it is not needed. If file can be big you can do it that way:

$h = fopen('text.txt', 'r');
$firstLine = fgets($h);
fseek($h, -3, SEEK_END);
$lastThreeChars = fgets($h);

Memory footprint is much lower

Jakub Filipczyk
  • 1,141
  • 8
  • 18
-1

That's from me:

$lines = file($pathToFile);
if ($lines[0] == 'START' && end($lines) == 'END') {
    // do stuff
}
Forien
  • 2,712
  • 2
  • 13
  • 30
-1

Reading whole file with fgets will be efficient for small siles. iF ur file is big then:

  1. open It and read first line
  2. use tail (i didn't check it but it looks OK) function I found in php.net in fseek documentation