PHP Terms Files Text Read

 

- Info:

- This tutorial shows how to use PHP to read from an existing text file.

- If file doesn't exists error is returned.

- The file pointer begins at the start of the file.

- Every time you read some characters file pointer is moved for that amount.

 

- Procedure:

- Create PHP Console Application Test.php

 

test.txt

First line.

Second line.

Third line.

 

test.txt (ASCII View)

46 69 72 73 74 20 6C 69 6E 65 2E 0A

53 65 63 6F 6E 64 20 6C 69 6E 65 2E 0A

54 68 69 72 64 20 6C 69 6E 65 2E 0A

 

Test.php

<?php

//Open file.-------------------------------------

$fileName = "test.txt";

$fp = fopen($fileName, 'r'); //Create FilePointer for writing to file.

if($fp==false) {

print("Unable to open file.");

exit(1);

}

//Read from file.--------------------------------

flock ($fp, LOCK_EX);

$firstLine = fgets($fp); //Read till next '\n' character.

$next5Bytes = fread($fp,5); //Read maximum of 5 following bytes.

$readCompleteFile = fread($fp,filesize($fileName));//Read complete file or what is left.

flock ($fp, LOCK_UN);

fclose($fp);

//Display file content.--------------------------

echo($firstLine ."<br/>");

echo($next5Bytes."<br/>");

echo($readCompleteFile);

?>