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.
Reading font
The fwrite() function in PHP is used to write data to a file.
Function Syntax:
int fwrite ( resource $handle , string $string [, int $length ] )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.:
$file = fopen("example.txt", "w");Write Data
Use fwrite() to write data to the file, e.g.: fwrite($file, "Hello, World!"); 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.: fwrite($file, "Hello, World!", 5); Only the first five characters "Hello" are written.
Check Write Success
Check the return value of fwrite(); if it is false, the write failed:
if (fwrite($file, "Hello, World!") === false) {
echo "Write failed";
} else {
echo "Write succeeded";
}Close the File
After writing, close the file with fclose() to release resources and ensure data is saved: fclose($file); 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.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.