PHP fwrite: How to Write Data to Files in PHP

actions, store settings, or even create log files for debugging. That’s where PHP fwrite comes in. It writes data to files and gives you more control over file storage.

In the tutorial, I will walk you through exactly how PHP fwrite works, from syntax and file modes to handling larger data. By the end, you will see just how handy this little function can be.

What is PHP fwrite

PHP fwrite is a function that writes data to a file. It seems a direct line between your PHP code and the file system—allowing you to add, update, or create new file content.

Whether you are appending information to an existing file or starting fresh, fwrite gives you the ability to write exactly what you need.

So, fwrite isn’t just about adding data to files; it’s also about how you manage that data. You get control over where it goes, how it’s formatted, and even whether it replaces or simply adds to the file content.

Using PHP fwrite starts with understanding its syntax. Here is what it needs:

  • File Handle – This is like your access pass to the file, which you get by opening the file with fopen.
  • Data to Write – The actual content you want to add to the file, which can be text, numbers, or any other data format.
  • length – This is optional, it contains the maximum number of bytes used to write the data of the file.

Here is its syntax:

fwrite(file, string, length)

Let’s see a quick example:

// Open the file for writing
$file = fopen("myfile.txt", "w"); 

// Write "Hello, World!" to the file
fwrite($file, "Hello, World!");    

// Close the file to save changes
fclose($file);

Here is what we did in the above example:

  • "myfile.txt" is opened in write mode ("w"), meaning it will clear the file if it exists or create it if it doesn’t.
  • fwrite then writes "Hello, World!" to that file.
  • fclose closes the file, which is important to avoid issues later.

As you can see, fopen affects fwrite, so without fopen, you won’t be able to use fwrite. Let’s move on to the section below to understand that.

How fopen Modes Affect fwrite in PHP

The mode you choose in fopen matters a lot—it decides how fwrite will behave with your file. 

  • "a+" (Append & Read) – Opens the file for reading and writing, adding new data to the end.
  • "w" (Write) – Opens the file for writing only. If it exists, all previous content is erased.
  • "a" (Append) – Adds data to the end of an existing file without deleting what’s already there.
  • "w+" (Write & Read) – Opens the file for both writing and reading, but clears any existing content.

So, choosing the right mode is necessary, especially when you want to keep existing content. If you’re logging events, for example, the "a" mode is perfect because it keeps adding to the file without removing previous entries.

Anyway, let’s see more examples:

Examples of fwrite in PHP

Here is a simple example of pushing small text to notes.txt file.

$file = fopen("notes.txt", "w");
fwrite($file, "Here’s a line of text.\n");
fwrite($file, "And here’s another line.");
fclose($file);

So, each fwrite call adds a line to notes.txt. The \n symbol is used to insert a new line, so each piece of data starts fresh.

In the example below, we will append data to an existing file:

$file = fopen("log.txt", "a");
fwrite($file, "New log entry added.\n");
fclose($file);

In this code, we open log.txt by using fopen in append mode, adding "New log entry added" to the end without deleting anything that’s already in the file.

Here is another example of how to handle large data with fwrite:

$file = fopen("bigdata.txt", "w");
// Repeats a string 1000 times
$largeData = str_repeat("Lots of data here.\n", 1000); 
fwrite($file, $largeData);
fclose($file);

We used str_repeat to create a large block of data. If you are working with something even bigger, try breaking it into smaller strings and write each piece separately.

let’s summarize it.

Wrapping Up

You learned how PHP fwrite lets you save data, build logs, and create static files, giving your PHP applications a way to interact with the file system. Here’s a quick recap of the main points:

  • PHP fwrite Definition – The function to write data to a file in PHP.
  • Syntax – You’ll need a file handle from fopen and the data you want to write.
  • File Modes – Choose from "w""a""w+", and "a+" to control how data is added.
  • Writing Data – Whether it’s single lines, multiple lines, or large blocks, fwrite handles it.
  • Large Data – Break down large data into smaller parts for smoother writing.
  • Practical Uses – From logs to user input, fwrite brings flexibility to file handling.

    Similar Reads

    PHP Math: Essential Functions with Examples

    PHP math may sound like a pretty simple thing, but I assure you it's a set of tools that will…

    PHP filter_var: Understand How to Sanitize Input

    PHP didn’t have a way to check or clean user input. Developers used scattered code—some wrote custom checks, others used…

    PHP Variadic Functions: Use Unlimited Arguments

    PHP Variadic functions show you a way to handle a variable number of arguments within a function. They are designed…

    PHP cURL: HTTP Requests and Responses in PHP

    In PHP, there are plenty of times when you need to connect with other servers or APIs. That's where the…

    Class and Object in PHP: How They Work with a Real Example

    Classes and objects are important parts of OOP in PHP. They help you organize your code so you can update…

    Abstract Class in PHP: How It Works & Examples

    Abstract class in PHP appeared to provide a way to define a structure for related classes and don't allow direct…

    Concatenating Strings in PHP: Tips and Examples

    In PHP, string operators, such as the concatenation operator (.) and its assignment variant (.=), are employed for manipulating and…

    PHP XML Parsers: Everything You Need to Know

    In PHP, manipulation of XML data can be very critical when most systems' data exchange relies on the format. XML—Extensible…

    PHP array_merge: Combine Multiple Arrays into One

    You have two or more arrays. You want one. That is the problem array_merge solves in PHP. This function lets…

    PHP List MongoDB Collections

    Sometimes, you may need to list collections with MongoDB in a PHP environment to manage or analyze your database structure.…

    Previous Article

    PHP fread Function: How to Read Files in PHP

    Next Article

    PHP fclose(): Close Access of File Manipulation

    Write a Comment

    Leave a Comment

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


    Subscribe to Get Updates

    Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
    No spam. Unsubscribe anytime.