PHP File Open/Read

As you know, PHP is a server side programming language and hence it allows user to work with the files and directories, which we stored on the web server. Today, you will learn how to open, read, and close the files and directory on your web server by using the PHP file functions.


1. FILE OPEN (fopen): It is used to open the file, i.e. using the open function; we open those files which is stored in a folder. In which we pass two parameters, the first parameter is the name of the file and second parameter is which mode we want to perform in an existing file.

For Example:

fopen(“Filename”,” r”);
Filename: It is file name that we want an open.
r : Reading operation in a file.

2. FILE READ (fread) : The fread function used to read the open file. In fread, we pass two parameters, the first parameter is the name of the file which we want to read and second parameter is the total numbers of bytes are read.

3. FILE CLOSE (fclose): It is used to close an open file.

Now come to the coding part……
Step 1: In this example we used a txtfile.txt file. This file is stored in a wamp/www folder.

Step 2: PHP code


// file is open using fopen function
$file = fopen("txtfile.txt", "r") or die ("doesn’t file exist");

// open file is read using fread function
echo fread($file, filesize("txtfile.txt"));

// close an open file




Leave a Reply

Notify of