How to Write Files in PHP Using fputs(): Syntax, Parameters, and Example
This guide explains the PHP fputs() function for writing data to files, covering its syntax, parameter details, return values, a complete code example, and important usage tips such as opening files with fopen() in write mode and closing them with fclose().
Overview
The fputs() function in PHP writes a string to an open file handle and returns the number of bytes written or false on failure.
Syntax
fputs ( resource $handle , string $string [, int $length ] ) : int|boolParameters
$handle : The file resource obtained from fopen().
$string : The string to be written to the file.
$length (optional): Maximum number of bytes to write; defaults to the length of $string.
Return Value
On success, the function returns the number of bytes written; on failure, it returns false.
Example Code
<?php
$file = fopen("demo.txt", "w");
if ($file) {
$content = "Hello, World!";
$length = fputs($file, $content);
if ($length !== false) {
echo "Write successful, wrote " . $length . " bytes.";
} else {
echo "Write failed.";
}
fclose($file);
}
?>The example opens demo.txt in write mode, writes the string "Hello, World!", checks the return value, and closes the file.
Important Notes
The file must be opened with a writable mode (e.g., "w") using fopen() before calling fputs().
Always close the file with fclose() after writing to release the resource.
Conclusion
The fputs() function provides a straightforward way to write strings to files in PHP, but developers must ensure proper file opening modes and remember to close the file handle to avoid resource leaks.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
