Read from a file in php

In previous post we learned how to write to a file using php. Here, we will learn how to read from a file in php. In php you can read intended number of characters, a line or whole content. There are various functions built in php to do these jobs. Let look at the important ones.

Reading with fgets

This function will read the first line from the file.

Reading with fread

This function will read specified number of characters from the first line. It takes two arguments, first is a file resource and second is number characters to read.
The above code will display first 5 characters of first line from the file.

Reading with file_get_contents

This function will read all content from a file.

A little bonus :
The function file_get_contents() is lot more useful than above. You can read an entire file on internet or load a complete webpage from another website into yours. Give it a try.

Posted in: PHP