Backend Development 4 min read

PHP fwrite() Function: Syntax, Parameters, Usage, and Examples

This article explains the PHP fwrite() function, covering its syntax, parameter details, return values, and practical usage examples such as opening files, writing data with optional length limits, checking success, and closing files, including notes on append mode.

php中文网 Courses
php中文网 Courses
php中文网 Courses
PHP fwrite() Function: Syntax, Parameters, Usage, and Examples

The fwrite() function in PHP is used to write data to a file.

Function Syntax:

<code>int fwrite ( resource $handle , string $string [, int $length ] )</code>

Parameter Description:

handle : required. The file resource handle returned by fopen() .

string : required. The string to write to the file.

length : optional. Maximum number of bytes to write; if omitted, the entire string is written.

Return Value:

On success, returns the number of bytes written; on failure, returns false .

Usage of fwrite():

Open a File

Use fopen() to open a file and obtain a file resource handle, e.g.:

<code>$file = fopen("example.txt", "w");</code>

Write Data

Use fwrite() to write data to the file, e.g.:

<code>fwrite($file, "Hello, World!");</code>

This writes "Hello, World!" into the opened file.

Specify Number of Bytes

You can limit the number of bytes written with the optional $length parameter, e.g.:

<code>fwrite($file, "Hello, World!", 5);</code>

Only the first five characters "Hello" are written.

Check Write Success

Check the return value of fwrite() ; if it is false , the write failed:

<code>if (fwrite($file, "Hello, World!") === false) {
    echo "Write failed";
} else {
    echo "Write succeeded";
}</code>

Close the File

After writing, close the file with fclose() to release resources and ensure data is saved:

<code>fclose($file);</code>

Note that fwrite() overwrites existing content; to append, open the file in append mode ("a") and then use fwrite() to add data at the end.

Summary

The fwrite() function writes data to a file by opening it, writing with optional byte limits, checking success, and finally closing it. It can also be used in append mode to add data without overwriting.

backendphpCode Examplefile handlingfwrite
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.