File Handling in PHP – Read, Write & Manage Files

What is File Handling in PHP?

File handling allows you to create, read, write, and delete files using PHP. It’s often used to:

  • Store user data in text files
  • Log activities (error logs, access logs)
  • Manage uploaded files
  • Generate reports dynamically

PHP File Handling Functions Overview

FunctionPurpose
fopen()Open a file
fread()Read from a file
fwrite()Write to a file
fclose()Close a file
file_exists()Check if file exists
unlink()Delete a file
file_get_contents()Read the entire file (shortcut)
file_put_contents()Write data to file (shortcut)

File Modes in fopen()

ModeDescription
'r'Read-only
'w'Write-only (overwrite existing)
'a'Write-only (append to end)
'x'Create new file, error if exists
'r+'Read and write
'a+'Read and append
'w+'Read and write (truncates file)

Opening and Writing to a File

Example:

PHP
<?php
$file = fopen("data.txt", "w"); // Open or create file in write mode
fwrite($file, "Hello from ScriptBuzz!");
fclose($file);
?>
  • If data.txt doesn’t exist, it’s created.
  • The file is overwritten if it already exists.

Reading from a File

Example:

PHP
<?php
$file = fopen("data.txt", "r");

while (!feof($file)) {
  $line = fgets($file);
  echo $line . "<br>";
}

fclose($file);
?>
  • fgets() reads line by line.
  • feof() checks for end-of-file.

Append to a File Without Overwriting

Use the a mode to add new content at the end of an existing file.

PHP
<?php
$file = fopen("data.txt", "a");
fwrite($file, "\nNew line added!");
fclose($file);
?>

Reading Entire File with file_get_contents()

This is a shortcut to read all contents into a string.

PHP
<?php
$content = file_get_contents("data.txt");
echo nl2br($content); // Preserve line breaks
?>

Writing Shortcut with file_put_contents()

PHP
<?php
file_put_contents("log.txt", "New log entry\n", FILE_APPEND);

You can pass FILE_APPEND to avoid overwriting.

Checking If File Exists Before Reading

PHP
<?php
if (file_exists("data.txt")) {
  echo "File found!";
} else {
  echo "File does not exist.";
}
?>
PHP
<?php
if (file_exists("old_data.txt")) {
  unlink("old_data.txt");
  echo "File deleted.";
}
?>

Permissions & Security Notes

  • PHP must have write permission on the file/folder
  • Never allow public users to write or delete files without sanitizing input
  • Avoid using user-supplied file names directly (to prevent path traversal attacks)

Real-World Examples

Example 1: Saving Feedback to a File

PHP
<?php
$name = $_POST['name'];
$feedback = $_POST['message'];

$file = fopen("feedbacks.txt", "a");
fwrite($file, "$name: $feedback\n");
fclose($file);
echo "Feedback saved!";
?>

Example 2: Simple Log System

PHP
$log = "[" . date("Y-m-d H:i:s") . "] User visited page\n";
file_put_contents("visit.log", $log, FILE_APPEND);

Common Mistakes

  • Forgetting to close files (fclose())
  • Using wrong file modes (e.g., w instead of a)
  • Not checking file existence before reading
  • Ignoring file permissions on the server
  • Not validating or sanitizing input before writing it to a file

Best Practices

  • Always close files after opening
  • Use file_put_contents() for simple cases
  • Check file_exists() before reading
  • Use absolute paths carefully
  • Never allow user to control file paths directly
  • Protect sensitive files from public access using .htaccess

Notes:

  • PHP allows full control over files: create, read, write, delete
  • fopen(), fwrite(), fread(), fclose() form the core of file handling
  • Use file_get_contents() and file_put_contents() for simple operations
  • Always handle files securely and close them properly

Practice Tasks

Task 1: Create a Note Saver
Build a form that accepts a message and appends it to a file called notes.txt.

Task 2: Read and Display
Read from a file called about.txt and display its content on a page.

Task 3: Delete File Option
Create a PHP script that deletes temp.txt only if it exists.