What is fwrite()
in PHP?
fwrite()
is a built-in PHP function used to write data to a file.
- It writes content to an open file (opened using functions like
fopen()
). - If the file doesn't exist and you opened it in a mode like
'w'
or'w+'
, it creates a new file. - You can specify how much to write by providing an optional third parameter (length).
Basic Syntax
fwrite(resource $stream, string $string, int $length = ?): int|false
- $stream — the file handle (opened using
fopen()
). - $string — the content you want to write.
- $length (optional) — how many bytes you want to write.
It returns the number of bytes written, or false
on failure.
Simple Example: Write to a File
<?php
$file = fopen("example.txt", "w"); // Open for writing, creates if not exists
if ($file) {
fwrite($file, "Hello, World!");
fclose($file); // Always close your file
echo "Data written successfully.";
} else {
echo "Unable to open the file.";
}
?>
🔹 This code will create (or overwrite) example.txt
and write "Hello, World!" inside it.
Example with Specifying Length
<?php
$file = fopen("example2.txt", "w");
if ($file) {
$text = "Welcome to PHP fwrite function!";
fwrite($file, $text, 7); // Only writes "Welcome"
fclose($file);
}
?>
🔹 Here, only the first 7 characters ("Welcome"
) will be written into the file.
Appending Data Instead of Overwriting
<?php
$file = fopen("example.txt", "a"); // 'a' mode means append
if ($file) {
fwrite($file, "\nThis is a new line!");
fclose($file);
}
?>
🔹 Using 'a'
mode, the new content is added at the end without removing existing content.
Important Points
- Always check if the file opened successfully before calling
fwrite()
. - Always close the file after writing with
fclose()
. - If you use
"w"
mode, it erases the existing content. - Use
"a"
mode to append without deleting the old content.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.