0
0
PhpHow-ToBeginner · 3 min read

How to Use fwrite in PHP: Syntax, Example, and Tips

In PHP, fwrite is used to write data to an open file resource. You first open a file with fopen, then use fwrite to write a string to it, and finally close the file with fclose.
📐

Syntax

The fwrite function writes data to a file resource. It requires two main parts: the file handle and the string to write.

  • file handle: The resource returned by fopen when opening a file.
  • string: The text or data you want to write to the file.
  • length (optional): Number of bytes to write from the string.
php
int fwrite(resource $handle, string $string, int $length = null)
💻

Example

This example opens a file called example.txt for writing, writes a line of text, and then closes the file.

php
<?php
$file = fopen('example.txt', 'w');
if ($file) {
    fwrite($file, "Hello, fwrite in PHP!\n");
    fclose($file);
    echo "Data written successfully.";
} else {
    echo "Failed to open the file.";
}
?>
Output
Data written successfully.
⚠️

Common Pitfalls

Common mistakes when using fwrite include:

  • Not opening the file before writing, which causes errors.
  • Forgetting to close the file with fclose, which can lead to data not being saved properly.
  • Using the wrong mode in fopen (e.g., reading mode r instead of writing mode w).
  • Not checking if fopen succeeded before calling fwrite.

Example of wrong and right usage:

php
<?php
// Wrong: fopen in read mode, then fwrite
$file = fopen('example.txt', 'r');
if ($file) {
    fwrite($file, "This will fail."); // Warning: fwrite() expects parameter 1 to be resource, boolean given
    fclose($file);
}

// Right: fopen in write mode
$file = fopen('example.txt', 'w');
if ($file) {
    fwrite($file, "This works fine.");
    fclose($file);
}
?>
📊

Quick Reference

  • fopen(filename, mode): Open a file. Use 'w' to write (overwrite), 'a' to append.
  • fwrite(handle, string): Write string to file.
  • fclose(handle): Close the file to save changes.
  • Always check if fopen returns a valid resource before writing.

Key Takeaways

Always open a file with fopen in write or append mode before using fwrite.
Check if fopen succeeded before calling fwrite to avoid errors.
Close the file with fclose to ensure data is saved properly.
Use fwrite to write strings or data to the file resource.
Avoid using fwrite on files opened in read-only mode.