To write to a file, open it with a write mode and use fwrite().
<?php
$handle = fopen("greeting.txt", "w");
fwrite($handle, "Hello, file!\n");
fwrite($handle, "This is the second line.\n");
fclose($handle);
echo file_get_contents("greeting.txt");
Hello, file!
This is the second line.
fwrite() writes exactly the text you give it. It does not add a new line, so include \n yourself.
The w mode empties the file
When you open a file in w mode, PHP deletes the old content immediately, before you write anything.
<?php
file_put_contents("data.txt", "old content that matters");
$handle = fopen("data.txt", "w"); // the old content is already gone
fclose($handle);
var_dump(filesize("data.txt"));
int(0)
If you want to keep what is there and add to it, use append mode, covered in the next lesson.
fwrite() returns the number of bytes
<?php
$handle = fopen("count.txt", "w");
$bytes = fwrite($handle, "abc");
fclose($handle);
var_dump($bytes);
int(3)
fwrite() returns false if writing failed (disk full, no permission). Check it when the data matters.
<?php
if (fwrite($handle, $text) === false) {
// log the problem and tell the user
}
Write several lines
<?php
$lines = ["name,age", "Ana,30", "Ben,25"];
$handle = fopen("people.csv", "w");
foreach ($lines as $line) {
fwrite($handle, $line . PHP_EOL);
}
fclose($handle);
echo file_get_contents("people.csv");
name,age
Ana,30
Ben,25
PHP_EOL is the correct line ending for the current system.
fputs()
fputs() is an alias for fwrite(). Use fwrite(), which is the common name.
Never overwrite by accident: mode x
Mode x creates a file and fails if it already exists. It protects existing files.
<?php
file_put_contents("report.txt", "existing");
$handle = @fopen("report.txt", "x");
var_dump($handle);
bool(false)
Permissions
The user that runs PHP (for example www-data) needs permission to write to the folder. If you see “failed to open stream: Permission denied”, fix the folder permissions. Do not make folders world-writable (777) on a real server.
Never write user input to a public file without care
.php or .html file), they can inject code or scripts. Save user data to non-executable files outside the public folder.