PHP open file and read file

PHP File Open and Read

In this php tutorial we will learn how to open file , read file and close file using file handling functions.

PHP functions :

  • fopen() – open file
  • fread() – read file
  • fclose() – close file

PHP fopen() function

PHP fopen() function used to open a file. If file does not exist then fopen() function will create a new file.
The fopen() function must use with mode character like ‘w’, ‘a’ ,’r’ etc.

PHP fopen() syntax:


fopen(“filename with extension”, “mode char”);


The fopen() function has following modes :

  • w = write only. if file exist open it, if not then create a new file.
  • w+ = read/write
  • r = read only
  • r += read / write
  • a = append file
  • a+ = read / append
  • x = write only. create new file, returns error if file already exists.
  • x+ = read/write.

Example of fopen() function


//open text file

//open ms word .doc file

//open pdf file



PHP Read file – fread() function

The fread() function used to reads from an open file. The read() function has two arguments.The first name of the file and second parameter specifies the maximum size of file to read.

PHP fread() syntax


fread(“filename”, “filesize”);


Example of fread() function

<title>PHP Read file</title>
<FORM method="POST">

<input type="submit" name="Submit1" value="Read File">

$filename = fopen( "abc.txt", "r" );

if( $filename == true )
$filesize = filesize("abc.txt" );
$filecontent = fread( $filename, $filesize );
fclose( $filename );

echo ( " File Content = $filecontent <br>" );
echo ( "File size : $filesize bytes" );
echo "Error !! Try again" ;


The output is :

PHP file open and read example
PHP file open and read example

PHP close file – fclose()

The fclose() function is used to close an open file.

PHP fclose() syntax




Exmaple of fclose() function


$file = fopen("abc.txt", 'w');



Leave a Reply

Your email address will not be published. Required fields are marked *