You are currently viewing fread() Function in PHP | Explained
  • Post category:PHP

fread() Function in PHP | Explained

fread in PHP

In this article, we will discuss what is fread() function in php. This function¬† ¬†is used to read the content of the file. It accepts two arguments, they are resource and file size. The file’s length can be found using the filesize() function. It takes the file name as its argument and returns the size of the file expressed in bytes.

The steps required to read a file with PHP are:

  • Open a file using fopen() function.
  • Get the file’s length using filesize() function.
  • Read the file’s content using fread() function.
  • Close the file with fclose() function.

Syntax:
string fread( resource $handle, int $length);

Ex:

<?php
$filename = "d:/wamp64/Ex1.txt";
$file = fopen($filename, "r");
if( $file == false){
echo ("Error in opening file");
exit();
}
$filesize = filesize($filename);
$filetext = fread($file, $filesize);
fclose($file);
echo ("File size: $filesize bytes");
echo ("<pre> $filetext</pre>");
?>

Output:
File size: 19 bytes
Hello PHP!
Welcome

Leave a Reply