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


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

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

(Visited 14 times, 1 visits today)

Leave a Reply

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

Captcha *