How to read from a textfile
TAGS: PHP, fopen, fread


Okay. In the last post we saw how to create, and write to, a textfile. That is a good thing, but then – it will be nice to be able to read that file again, later. How do we do that? If you thought that is was simple to write, then look at this. It is also very simple to read from a textfile. First we assign a variable the name of our file. Here just “file.txt”. If you need it, then remember a path. Then we open the file for Read only ('r'). We read all content in to a new vaiable named $String, and we make sure to get all content by specifying the size of what we want to read. It could be 24, meaning 24 characters, but we don't know the size maybe, so here we want as many as the complete size of the file – shortly: filesize($filename) - All.
<?php
$filename = 'file.txt'; 
$file = fopen($filename, 'r');
$string = fread( $file, filesize($filename) ); 
echo $string;
?>

fopen have following options;
'r' (read only, file pointer at the beginning) 
'r+' (read and write, file pointer at the beginning) 
'w' (write only, file pointer at the beginning, zero length file, create it 
if it does not exist) 
'w+' (read and write, file pointer at the beginning, zero length file, 
create it if it does not exist) 
'a' (write only, file pointer at the end, zero length file) 
'a+' (read and write, file pointer at the end, zero length file) 
'x' (write only, file pointer at the beginning, if exists, return FALSE) 
'x+' (read and write, file pointer at the beginning, if exists, return FALSE)