Skip to content

PHP Tutorial File Handling

Writing Files

Lesson 166 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

To write to a file, open it with a write mode and use fwrite().

index.php
PHP
<?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");
Output
OUTPUT
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.

index.php
PHP
<?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"));
Output
OUTPUT
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

index.php
PHP
<?php
$handle = fopen("count.txt", "w");

$bytes = fwrite($handle, "abc");

fclose($handle);

var_dump($bytes);
Output
OUTPUT
int(3)

fwrite() returns false if writing failed (disk full, no permission). Check it when the data matters.

index.php
PHP
<?php
if (fwrite($handle, $text) === false) {
    // log the problem and tell the user
}

Write several lines

index.php
PHP
<?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");
Output
OUTPUT
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.

index.php
PHP
<?php
file_put_contents("report.txt", "existing");

$handle = @fopen("report.txt", "x");

var_dump($handle);
Output
OUTPUT
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.

dangerous
Never write user input to a public file without care
If a visitor controls the text and the file is served by the web server (a .php or .html file), they can inject code or scripts. Save user data to non-executable files outside the public folder.