PHP File Open / Read / Close

PHP Tutorial

PHP File Open / Read / Close

In PHP, file handling allows you to open, read, write, and close files stored on the server.
This is very important for logs, configuration files, data storage, and real-world applications.


 What is File Handling in PHP?

File handling in PHP means:

  • Opening a file

  • Reading data from it

  • Writing data to it

  • Closing the file

 PHP provides built-in functions for file handling.


 File Open – fopen()

Syntax

fopen(filename, mode);

Common File Modes

ModeMeaning
rRead only (file must exist)
wWrite only (creates/overwrites)
aAppend (adds data at end)
r+Read & write
w+Read & write (overwrite)
a+Read & append

Example: Open a File


 File Read – fread()

Syntax

fread(file_pointer, size);

Example: Read Entire File

 Reads full content of the file


Read File Line by Line – fgets()


 

 Very useful for large files


Read File Character by Character – fgetc()


 


File Close – fclose()

Syntax

fclose(file_pointer);

Why Close a File?

  •  Frees server memory
  •  Prevents file corruption
  • Good programming practice
  •  Always close files after use.

 Shortcut Functions (Very Common)

file_get_contents()

Reads entire file in one line.

readfile()

Reads and outputs file directly.


 File Exists Check – file_exists()

 Avoids runtime errors


 Error Handling with Files


 Common Mistakes

  •  Forgetting to close file
  •  Using wrong file mode
  •  Not checking file existence
  •  Reading large files with fread()

Interview Questions & MCQs (Very Important)

Q1. Which function opens a file in PHP?

A) open()
B) file()
C) fopen()
D) read()

Answer: C


Q2. Which mode opens a file for reading only?

A) w
B) a
C) r
D) x

Answer: C


Q3. Which function reads a file line by line?

A) fread()
B) fgets()
C) fgetc()
D) readfile()

Answer: B


Q4. Which function closes a file?

A) close()
B) stop()
C) end()
D) fclose()

Answer: D


Q5. Which function reads entire file easily?

A) fread()
B) file_get_contents()
C) fgets()
D) fopen()

Answer: B


Q6. Why is fclose() important?

A) Speeds PHP
B) Frees memory
C) Prevents corruption
D) All of the above

Answer: D


 Real-Life Use Cases

  •  Reading configuration files
  •  Displaying text files
  •  Logging user activity
  •  File-based data storage

 Summary

  • fopen() → open file

  • fread(), fgets(), fgetc() → read file

  • fclose() → close file

  • Always check file existence

  • Use shortcut functions for simplicity

  • Very important for PHP exams & interviews

You may also like...