PHP fwrite( ) Function (original) (raw)

Last Updated : 31 May, 2025

The fwrite() function in PHP is used to write data (string or binary) to an open file. Before using fwrite(), you need to open the file with fopen(). Once the file is open, fwrite() sends your data to that file.

**Syntax:

fwrite(resource handle,stringhandle, string handle,stringstring, int $length = null): int|false

**In this syntax:

The fwrite() function in PHP accepts three parameters.

**Return Value:

It returns the number of bytes written on success, or False on failure.

**Note: The fwrite() function was initially introduced in core PHP 4 and continues to be fully supported in PHP 5, PHP 7, and PHP 8.

How Does fwrite() Work?

The general process of writing to a file using fwrite() involves these steps:

Writing to a New File

We open the file example.txt in write mode ("w"). Then, we write a string of text into the file using fwrite(). After writing, we close the file with fclose() to save the changes.

PHP `

handle=fopen(handle = fopen(handle=fopen(file, "w"); if ($handle) { $text = "Hello, this is a sample text.\nWelcome to fwrite() function."; bytesWritten=fwrite(bytesWritten = fwrite(bytesWritten=fwrite(handle, $text); echo "Wrote bytesWrittenbytestobytesWritten bytes to bytesWrittenbytestofile"; fclose($handle); } else { echo "Failed to open the file."; } ?>

`

**Output:

Screenshot-2025-05-31-162809

PHP fwrite( ) Function

Appending Data to an Existing File

We open the file example.txt in append mode ("a"), which lets us add data without deleting what’s already there. Then, we write a new line at the end of the file using fwrite(). Finally, we close the file with fclose().

PHP `

handle=fopen(handle = fopen(handle=fopen(file, "a"); if ($handle) { $newLine = "\nAdding a new line to the file."; fwrite($handle, $newLine); fclose($handle); echo "Data appended successfully."; } else { echo "Unable to open the file."; } ?>

`

**Output:

file

Writing Binary Data to a File

In this example, we open a file named data.bin in binary write mode. We then create some binary content using PHP’s pack() function to convert numbers into binary format. This binary data is written to the file, and finally, the file is closed.

PHP `

`

**Output:

Screenshot-2025-05-31-164634

PHP fwrite( ) Function

Best Practices for Using the fwrite() Function

Conclusion

The PHP fwrite() function is essential for writing data to files. It works together with fopen() to open files and fclose() to close them. Whether you want to create new files, update existing ones, or write partial data, fwrite() provides an efficient way to do so.With proper error handling and the right file modes, you can safely and effectively manage file writing operations in your PHP applications.