Using PHP fwrite() to Write Data to Files

This article explains how the PHP fwrite() function writes strings to an open file handle, describes its parameters and return values, and provides a complete example demonstrating file existence checks, opening in append mode, writing content, handling errors, and closing the file.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using PHP fwrite() to Write Data to Files

fwrite() writes a string to an open file pointer, optionally limiting the number of bytes written.

Parameters: handle – the file resource returned by fopen(); string – the data to write; length – optional maximum number of bytes to write.

Return value: the number of bytes written, or FALSE on error.

Example usage:

<?php
$filename = 'test.txt';
$somecontent = "Add these lines to the file
";
if (is_writable($filename)) {
    $handle = fopen($filename, 'a');
    if (!$handle) {
        echo "Cannot open file $filename";
        exit;
    }
    if (fwrite($handle, $somecontent) === FALSE) {
        echo "Cannot write to file $filename";
        exit;
    }
    echo "Successfully wrote $somecontent to $filename";
    fclose($handle);
} else {
    echo "File $filename is not writable";
}
?>

The script first checks that the target file exists and is writable, opens it in append mode, writes the specified content, reports success or failure, and finally closes the file handle.

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.

BackendTutorialfile writefile-handlingfwrite
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

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.