Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 14

File Handling in PHP (Read, Write, Append)

In this lesson: Read, write and append files in PHP with fopen, fwrite, fgets, file_get_contents and file_put_contents — code and output.

Why file handling

File handling lets PHP save data to a file and read it back later — useful for logs, simple settings, exports, or storing text when you do not need a full database. PHP makes the common cases very easy with two functions: file_put_contents and file_get_contents.

💡 For small text jobs, file functions are enough. For lots of structured data, use a database like MySQL instead.

Write to a file

file_put_contents creates the file (if needed) and writes text into it.

<?php
  file_put_contents("data.txt", "Hello CodingEasily");
  echo "Saved!";
?>
Saved!

Warning: this replaces everything already in the file. To keep old content and add to it, use append (next).

Read a file

<?php
  $text = file_get_contents("data.txt");
  echo $text;
?>
Hello CodingEasily

file_get_contents returns the whole file as one string. Simple and perfect for small files.

Append to a file

Add the FILE_APPEND flag to add to the end instead of replacing.

<?php
  file_put_contents("log.txt", "Line 1\n");
  file_put_contents("log.txt", "Line 2\n", FILE_APPEND);
  echo file_get_contents("log.txt");
?>
Line 1
Line 2

Without FILE_APPEND, "Line 2" would have erased "Line 1". Appending is how you build up logs.

fopen for line-by-line

For big files, open a handle and read line by line so you do not load everything at once.

<?php
  $f = fopen("log.txt", "r");   // "r" = read mode
  while (($line = fgets($f)) !== false) {
      echo $line;
  }
  fclose($f);
?>
Line 1
Line 2

Always fclose() when done. Common modes: "r" read, "w" write (erase), "a" append.

Check and delete

<?php
  if (file_exists("data.txt")) {
      echo "File is there";
      // unlink("data.txt");  // deletes the file
  }
?>
File is there

file_exists checks before you read or delete. unlink removes a file — use it carefully.

Common mistakes

  • Overwriting instead of appending. Plain file_put_contents replaces; add FILE_APPEND to keep old data.
  • Wrong path. A relative path is based on the script's location — check it if the file is not found.
  • Permission errors. The folder must be writable by the web server.
  • Forgetting fclose(). Always close a file you opened with fopen.

Summary

  • file_put_contents writes; file_get_contents reads a whole file.
  • Add FILE_APPEND to add to the end instead of replacing.
  • Use fopen + fgets for large files, line by line, then fclose.
  • file_exists checks; unlink deletes.
  • For lots of structured data, use MySQL instead of files.

Next, store structured data in MySQL, or export data with PHP CSV export.

Frequently Asked Questions

What is the easiest way to write to a file in PHP?
Use file_put_contents("data.txt", $text). It creates the file if it does not exist and writes your text in one line. It is the simplest way for small files.
How do I read a whole file in PHP?
Use file_get_contents("data.txt"). It returns the entire file content as a string. For reading line by line, use fopen with fgets in a loop.
What is the difference between write and append?
Writing (default) replaces everything in the file. Appending adds to the end and keeps the old content. Use file_put_contents($f, $text, FILE_APPEND) to append.
Why does my file write fail?
Usually it is a permissions problem — PHP does not have permission to write in that folder. Make sure the folder is writable, and use a correct relative or absolute path.
When should I use fopen instead of file_get_contents?
Use fopen when the file is large or you want to process it line by line, so you do not load the whole file into memory at once. For small files, file_get_contents is simpler.
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicOOP in PHP Your progress: 14 / 50 (28%) · Lesson 15 / 50 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free