What is fwrite()
in PHP?
fwrite()
is a built-in PHP function used to write data to a file. It's one of the fundamental file handling functions in PHP for writing content to files on the server.
Syntax
fwrite(resource $handle, string $string, int $length = ?): int|false
Parameters
$handle
: A file pointer resource created byfopen()
$string
: The data to write to the file$length
(optional): Maximum number of bytes to write
Return Value
- Returns the number of bytes written on success
- Returns
false
on failure
Basic Usage Examples
1. Writing to a File
<?php
// Open file for writing
$file = fopen("example.txt", "w");
if ($file) {
// Write content to file
$bytesWritten = fwrite($file, "Hello, World!");
echo "Bytes written: " . $bytesWritten;
// Close the file
fclose($file);
} else {
echo "Could not open file!";
}
?>
2. Appending to a File
<?php
// Open file for appending (content added to end)
$file = fopen("example.txt", "a");
if ($file) {
fwrite($file, "\nThis is appended text.");
fclose($file);
echo "Content appended successfully!";
}
?>
3. Writing with Length Limit
<?php
$file = fopen("example.txt", "w");
$text = "This is a long text string";
// Write only first 10 bytes
fwrite($file, $text, 10);
// File contains: "This is a"
fclose($file);
?>
File Mode Examples
Mode | Description | File Pointer Position |
---|---|---|
"w" |
Write only. Creates file if doesn’t exist, truncates if exists | Beginning |
"a" |
Write only. Creates file if doesn’t exist, appends if exists | End |
"x" |
Write only. Creates file, returns FALSE if file exists | Beginning |
"c" |
Write only. Creates file if doesn’t exist, doesn’t truncate | Beginning |
Practical Examples
1. Logging Messages
<?php
function logMessage($message) {
$file = fopen("app.log", "a");
if ($file) {
$timestamp = date('Y-m-d H:i:s');
fwrite($file, "[$timestamp] $message\n");
fclose($file);
}
}
logMessage("User logged in");
logMessage("File uploaded successfully");
?>
2. Writing CSV Data
<?php
function writeCSV($filename, $data) {
$file = fopen($filename, "w");
if ($file) {
foreach ($data as $row) {
fputcsv($file, $row); // fputcsv uses fwrite internally
}
fclose($file);
return true;
}
return false;
}
$data = [
['Name', 'Email', 'Age'],
['John Doe', 'john@example.com', 30],
['Jane Smith', 'jane@example.com', 25]
];
writeCSV("users.csv", $data);
?>
3. File Upload Handling
<?php
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
$uploadedFile = $_FILES['file']['tmp_name'];
$destination = "uploads/" . $_FILES['file']['name'];
$source = fopen($uploadedFile, "r");
$dest = fopen($destination, "w");
// Copy file chunk by chunk (good for large files)
while (!feof($source)) {
$chunk = fread($source, 8192); // 8KB chunks
fwrite($dest, $chunk);
}
fclose($source);
fclose($dest);
echo "File uploaded successfully!";
}
?>
Error Handling
<?php
$file = @fopen("example.txt", "w");
if (!$file) {
die("Error: Could not open file for writing");
}
$result = fwrite($file, "Some content");
if ($result === false) {
die("Error: Could not write to file");
}
echo "Successfully wrote $result bytes to file";
fclose($file);
?>
Best Practices
- Always check if file opened successfully
- Handle errors appropriately
- Close files with
fclose()
when done - Use appropriate file modes (
w
,a
,x
,c
) - Consider file permissions on the server
- Use
FILE_APPEND
flag withfile_put_contents()
for simpler append operations
Alternative: file_put_contents()
For simpler write operations, you can use:
<?php
// Write to file (overwrites existing content)
file_put_contents("example.txt", "Hello World!");
// Append to file
file_put_contents("example.txt", "New line\n", FILE_APPEND);
// Lock file while writing
file_put_contents("example.txt", "Content", LOCK_EX);
?>
fwrite()
gives you more control over the writing process, especially useful for large files or when you need to write data in chunks.
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.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.