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 IF Statement: A Guide to Conditional Logic

    The IF statement in PHP helps to see if a condition is true or not. If it is true, it…

    PHP array_diff: How it Works with Examples

    The array_diff function compares arrays and returns values that exist in the first array but not in the others in…

    PHP explode Function: How it Works with Examples

    When you deal with text in PHP, sometimes you need to break it into parts. This is common when users…

    PHP Boolean: Assigning True or False to a Variable

    You can assign the boolean data type to PHP variables or use it as a direct value. This enables you…

    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…

    Understanding the PHP Operator Precedence

    The PHP operator precedence refers to when doing a calculation for three or more numbers, they are calculating its values…

    PHP str_replace Function: How it Works with Examples

    If you find a word that does not fit and want to fix it. You can use the PHP str_replace…

    PHP OR Operator: Using || and or in Conditional Statements

    The PHP OR operator has two renditions: either || or or. Both of these are useful logical operators when you want to introduce…

    PHP htmlspecialchars Function: Prevent XSS in HTML Output

    A PHP script can break the page or allow code injection if it outputs user input directly into HTML. The…

    PHP array_intersect Function: How it Works with Examples

    The PHP array_intersect function finds common values in arrays and returns matches as a new array. Understand the array_intersect in…

    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.