PHP File Open/Read

The fopen() function is used to open a file. The basic syntax of fopen() is :
 fopen(filename, mode)
Where the first parameter filename specifies the name of the file we want to open, and the second parameter mode specifies in which mode the file should be opend. For example :
 $myfile = fopen("myfile.txt", "r")
The fread() function is used to read a specified number of characters from a file. The basic syntax of fread() function is :
 fread(file_pointer, file_size)
Where the first argument is the file pointer or file handle, and the second argument file_size is nothing but the size or length of file in bytes. Now lets see some example,

  $file = "file.txt";

  if (file_exists($file)) {
    $myfile = fopen($file, "r") or die("Error : Cannot open the file.");     
    $size = filesize($file);        
    $file_content = fread($myfile, $size); 
    echo $file_content;
  } else {
    echo "File does not Exists.";

Output :

This is Test String.

At the above code, the file_exists() function is used to check that, weather the file is exists or not.

Next Topic :