File Handling in PHP

File Handling comes into picture in almost every web application, which basically deals with opening a file, reading it and performing operations on data.

Opening and closing a file:

Below is how we do it –

For example –

fopen function always returns a Boolean. It returns false if the concerned file is not found or any error is encountered while opening the file.

filesize function returns the size of the concerned file in bytes.


fclose function closes the respective opened file and releases all of its allocated memory.

File modes:

Most commonly used file modes include –

r – To open a file to read

w – To open a file to write only. Creates a new file if the file is not found. File pointer always at the beginning of the file when opened. Existing data gets erased.

a – To open a file to write only. Creates a new file if the file is not found. File pointer at the end of the file. Existing file data remains as it is.

x – Writes to the file only if the file doesn’t pre-exist. If the file already exists, fopen returns false.

Reading a file:

When a file is opened using fopen, the file pointer points to the start of first line. After every fgets within the loop, the pointer keeps moving to the next line, until the end of file is detected. feof function helps in identifying the end of file.

fread function reads the content of the file as a whole different from what fgets does, which reads the file line by line.

Writing a file:

When trying to open a file in write mode, it first tries to search the file in the respective directory. If the file is found, it is opened and all its content gets cleared and the new contents are written. If the file is not found, a new file with the same gets created and the new contents get written into it. For example, in the above snippet, there is a new file xyz.txt that gets created at the same location. On opening this file, we can see the following content –

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.