Current Location: Home> Latest Articles> PHP File Writing Function fputs() Explained: Usage and Example Guide

PHP File Writing Function fputs() Explained: Usage and Example Guide

M66 2025-06-17

PHP Function Introduction—fputs(): Write Content to a File

In PHP, the fputs() function is used to write a string to an open file. The basic syntax is as follows:

<span class="fun">fputs(resource $handle, string $string[, int $length]) : int|bool</span>

Parameter Explanation

  • $handle: The file resource handle, usually obtained through the fopen() function.
  • $string: The string content to be written to the file.
  • $length: An optional parameter that specifies the maximum number of bytes to write. By default, it writes the entire length of the string.

Return Value

The function returns the number of bytes written if successful, or false on failure.

Example Code

<?php
$file = fopen("demo.txt", "w");
<p>if ($file) {<br>
$content = "Hello, World!";<br>
$length = fputs($file, $content);</p>
    echo "Write successful, a total of " . $length . " bytes written.";
} else {
    echo "Write failed.";
}

fclose($file);

}
?>

The example above opens a file named demo.txt and writes the string "Hello, World!" into it. If successful, it returns the number of bytes written, or false on failure.

Important Notes

When using fputs() to write to a file, make sure the file is opened in a writable mode. In the example, we used fopen() with the write mode ("w") to open the file. After writing, we used fclose() to close the file and release resources.

Conclusion

The fputs() function is a commonly used function in PHP for writing content to files. Understanding its parameters and return values helps in performing efficient file operations and data storage.