How to Write Files in PHP Using fputs(): Syntax, Parameters, and Example

This article explains the PHP fputs() function for writing data to files, detailing its syntax, parameters, return values, and provides a complete code example that demonstrates opening a file, writing a string, handling success or failure, and properly closing the file.

php Courses
php Courses
php Courses
How to Write Files in PHP Using fputs(): Syntax, Parameters, and Example

Function Syntax

The PHP fputs() function writes a string to an open file handle. It is an alias of fwrite().

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

Parameters

$handle – A valid file resource obtained from fopen() (or another function that returns a stream).

$string – The data to be written to the file.

$length (optional) – The maximum number of bytes to write. If omitted, the entire length of $string is written.

Return Value

On success the function returns the number of bytes actually written. On failure it returns false.

Example

<?php
$file = fopen("demo.txt", "w"); // open for writing, creates file if it does not exist
if ($file) {
    $content = "Hello, World!";
    $bytesWritten = fputs($file, $content); // write the string
    if ($bytesWritten !== false) {
        echo "Write successful, wrote {$bytesWritten} bytes.";
    } else {
        echo "Write failed.";
    }
    fclose($file); // always close the handle to free the resource
}
?>

Important Notes

The file must be opened with a mode that permits writing (e.g., "w", "a", "r+", etc.).

Always close the file with fclose() after writing to release the underlying resource.

If you need to write binary data, use a binary mode such as "wb" on Windows.

When $length is specified and is smaller than the string length, only the first $length bytes are written.

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.

BackendCode Examplefile-handlingfputs
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.