I have to FTP a potentially large text file, and before I process it I want to make sure I got the whole thing and as a byproduct verify it contains a valid trailer record. The file is pipe-delimited, and fields may or may not be double-quote encased. A trailer record (and only a trailer record) will be in the format "TTn|n" (where "n" will be one or more digits). This was the best solution I could come up with that did not have to parse the whole file nor load it into memory. I'm just curious if anyone has a "better" solution. I considered using shel_exec() along with the "tail -200" command, but prefer not to depend on OS commands if I don't have to.
/**
* See if we got the whole file by looking for the trailer record
* @return boolean
* @param string path to file
*/
function isFullFile($filePath)
{
$fh = fopen($filePath, 'r');
if($fh === false) {
return false;
}
fseek($fh, -200, SEEK_END);
$line = fgets($fh); // make sure we start following loop after a line break
while(($line = fgets($fh)) !== false) {
$line = trim($line);
$line = trim($line, '"');
$fields = preg_split('#"?|"?#', $line);
if(!empty($fields[0])) {
if(preg_match('#^TT\d+$#', $fields[0])) {
return true;
}
}
}
return false;
}