Backend Development 3 min read

Using PHP fputs() to Write Data to Files

This article explains the PHP fputs() function, its syntax, parameters, return values, and provides a complete example showing how to open a file with fopen(), write a string, check the result, and close the handle with fclose() to ensure proper file I/O handling.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP fputs() to Write Data to Files

In PHP, the fputs() function is used to write data to a file. Its syntax is:

fputs ( resource $handle , string $string [, int $length ] ) : int|bool

Parameter Description:

$handle : the file resource handle, typically obtained via fopen() .

$string : the string to be written.

$length (optional): the maximum number of bytes to write; defaults to the length of $string .

Return Value:

On success, the number of bytes written is returned; otherwise false is returned.

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 a file named demo.txt in write mode, writes the string "Hello, World!" using fputs() , checks whether the write succeeded, outputs the result, and finally closes the file with fclose() to release the resource.

Note that when using fputs() , the file must be opened in a writable mode (e.g., with fopen() in "w" mode). After writing, always close the file handle with fclose() to ensure proper resource cleanup.

Summary

The fputs() function in PHP provides a straightforward way to write strings to files; proper use requires opening the file with a writable mode and closing the handle after the operation to maintain correctness.

backend developmentphpFile I/Ofopenfputsfclose
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.