Using PHP fputs() to Write Data to Files

The article explains PHP's fputs() function, detailing its syntax, parameters, return values, and provides a complete example showing how to open a file with fopen(), write a string, handle the result, and close the file with fclose() to ensure proper resource management.

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.

Syntax:

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

Parameters:

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

$string : the string to be written.

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

Return value:

Returns the number of bytes written on success, or false on failure.

Example:

<?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 script opens demo.txt for writing, writes the string “Hello, World!”, checks the result, and closes the file to release the resource.

Note that the file must be opened in a writable mode (e.g., using fopen() with the “w” flag) before calling fputs(), and you should always close the handle with fclose() after writing.

Summary

The fputs() function provides a straightforward way to write strings to files in PHP, but proper opening modes and closing of file handles are essential for correct operation.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPfile-handlingfputswriting files
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

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.