Writing Files in PHP for Beginners

Introduction

Writing data to files is a common requirement in PHP applications. Whether you are saving user input, storing logs, or generating reports, file writing is an essential backend skill.

Think of writing files like editing a notebook:

  • Write (w) → erase old content and write new
  • Append (a) → add new content at the end

In this tutorial, you will learn how to write files in PHP step by step using simple and practical examples.

What You Will Learn

  • How to create and write files in PHP
  • Difference between overwrite and append modes
  • How to use fwrite() and file_put_contents()
  • How to check file permissions
  • Common mistakes and security tips

Why Write Files in PHP?

Writing files is useful for:

  • Saving user data
  • Creating log files
  • Storing temporary information
  • Writing reports
  • Debugging applications

Many real-world PHP systems (including CMS platforms) use file writing internally.

Writing Files Using fopen() and fwrite()

The fopen() function opens a file, and fwrite() writes data into it.

Example: Create or Overwrite a File

$file = fopen("example.txt", "w");
fwrite($file, "Hello, this is written using PHP.");
fclose($file);

Explanation

  • fopen() opens the file in write mode (w)
  • If the file does not exist → it will be created
  • If the file exists → its content will be deleted
  • fwrite() writes data to the file
  • fclose() closes the file

Output

The file example.txt will contain:

Hello, this is written using PHP.

Appending Data to a File

To add data without deleting existing content, use append mode.

Example

$file = fopen("example.txt", "a");
fwrite($file, "\nThis line is appended.");
fclose($file);

Output

Hello, this is written using PHP.
This line is appended.

💡 This method is commonly used for log files.

Writing Files Using file_put_contents() (Recommended)

The file_put_contents() function provides a faster and simpler way to write files.

Example

file_put_contents("example.txt", "This text is written using file_put_contents.");

Append Data Example

file_put_contents("example.txt", "\nMore text added.", FILE_APPEND);

Why Use This?

  • Simple and clean
  • No need to open or close files manually
  • Best for quick tasks

Checking File Permissions Before Writing

Before writing, always ensure the file is writable.

Example

if (is_writable("example.txt")) {
    file_put_contents("example.txt", "Writing successful.");
} else {
    echo "File is not writable.";
}

Common File Writing Modes

ModeDescription
wWrite (overwrite)
aAppend
w+Write & read
a+Append & read

Difference Between fwrite() and file_put_contents()

FunctionWhen to Use
fwrite()When using fopen() and need more control
file_put_contents()Quick and simple file writing

👉 Simple rule:
Use file_put_contents() for most cases, and fwrite() when you need more control.

When Should You Use Each Method?

  • Use file_put_contents() → when you want quick and simple writing
  • Use fopen() + fwrite() → when you need full control
  • Use append mode (a) → for logs and history
  • Use write mode (w) → when replacing content

Real-World Example: Saving User Messages

Let’s create a simple system that stores user messages in a file.

$name = "John";
$message = "Hello, this is a message.\n";
file_put_contents("messages.txt", $name . ": " . $message, FILE_APPEND);

Output (messages.txt)

John: Hello, this is a message.

👉 This works like a mini database for small applications.

Best Practices for Writing Files in PHP

  • Always use append mode for logs
  • Avoid overwriting important files
  • Check file permissions before writing
  • Use proper file paths
  • Close files properly when using fopen()
  • Sanitize user input before writing

Common Mistakes to Avoid

  • Overwriting files unintentionally
  • Forgetting newline characters
  • Writing without permission checks
  • Storing sensitive data in plain text
  • Not closing files
  • Writing user input directly without validation

Security Best Practices

  • Never store passwords in files
  • Restrict file permissions
  • Validate user input before writing
  • Avoid writing files in public directories

FAQs

What is the easiest way to write files in PHP?

file_put_contents() is the easiest and fastest method.

How do I append data to a file in PHP?

Use FILE_APPEND with file_put_contents() or use mode a with fopen().

What is the difference between w and a mode?

w → overwrites the file
a → appends data to the file

Practice Task

  • Create a file called notes.txt
  • Write a PHP script to save a message
  • Append a new message every time the page reloads
  • Display the file content

Summary

  • PHP allows easy file writing
  • fopen() and fwrite() give more control
  • file_put_contents() is quick and simple
  • Always handle file permissions carefully

In the next tutorial, you’ll learn about File Upload in PHP.

Related Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *