PHP

 Home  Computers & Internet  Web Programming PHP
What is PHP?
Echo
Comments
Variables
Constants
Data Types
number_format()
Character Strings
Mathematical Operators
Comparison Operators
Logical Operators
Joining Strings
explode()
implode()
strtolower()
strtoupper()
strlen()
ucfirst()
ucwords()
strrev()
str_replace()
str_repeat()
trim()
strip_tags()
addslashes()
stripslashes()
strpos()
strrpos()
nl2br()
isset()
unset()
empty()
POST
GET
If Statements
If Else Statements
Elseif Statements
Switch Statements
For Loops
While Loops
Do While Loops
Foreach Loops
File Create
File Open
File Read
File Write
File Delete
fgets()
file_get_contents()
Date & Time
$_SERVER
Sessions
Cookies
Arrays

HOW TO READ FILES USING THE fread() FUNCTION IN PHP

The fread() function is used to read from a file that is opened. It takes as parameters, the resource file handle and the length in bytes of the file. It reads from this file to the specified length or till the end of file, whichever comes first.

The general format is:

fread(filehandle, length in bytes);

Example:

<?

$myFile="test.txt";
$fd=fopen($myFile, "r");
$contents=fread($fd, "100");
fclose($fd);

?>

First, we use the fopen function to open the file in read or write mode. Then we use the fread function to read file to 100 bytes. We then close the file using the fclose function. $contents variable then holds the contents of the file. If you echo $contents, you will see the contents of the file outputted to your screen.

If you want to read the entire file but do not know the entire size of the file in bytes, then use the handy filesize() function in the fread() function as follows:

<?

$myFile="test.txt";
$fd=fopen($myFile, "r");
$contents=fread($fd, filesize($myFile));
fclose($fd);

?>

Home | Privacy Policy | Terms Of Use | Contact Us