PHP File Handling

What is File Handling?

File handling allows PHP to create, read, write, and manage files on the server.

This is useful for saving data, writing logs, and reading stored information.

Opening Files

Use fopen() to open a file.

Loading...
Output:

File Modes

  • "r" — read only
  • "w" — write only and clears existing content
  • "a" — append to the end of the file
  • "x" — create a new file only

Reading a File

Use fread() to read file contents.

Loading...
Output:

Writing to a File

Use fwrite() to write data to a file.

Loading...
Output:

Appending to a File

Use append mode "a" to add content without deleting existing content.

Loading...
Output:

Reading Line by Line

Use fgets() to read one line at a time.

Loading...
Output:

Checking if a File Exists

Use file_exists() before reading or deleting a file.

Loading...
Output:

Deleting a File

Use unlink() to delete a file.

Loading...
Output:

Full Example

Loading...
Output:

Why File Handling is Important

  • Save user data
  • Store logs
  • Read configuration files
  • Work with generated files

Common Mistakes

  • Forgetting to use fclose()
  • Using "w" when you meant "a"
  • Reading a file before checking if it exists
  • Not checking if fopen() failed

Practice

Create a PHP script that writes a message to a file, reads it, and prints the content.

Loading...
Output:

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic