bhylu.com

Advertisements

PHP Writing Files

Writing a file changes state. Decide whether the operation should create, replace or append before choosing the API and mode.

How it works

file_put_contents replaces an existing file unless flags change that behaviour. fopen with x requires a new file, while append modes have a different contract. Check write results rather than assuming every byte was stored successfully. A temporary file is appropriate for this demonstration because replacing its known content cannot destroy someone else’s work. Multi-process consistency and atomic replacement need a deliberate storage design.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l file-write.php
php file-write.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · file-write.php

<?php
declare(strict_types=1);

$file = tempnam(sys_get_temp_dir(), "bhylu-write-");
if ($file === false) throw new RuntimeException("Cannot create file");
try {
    $written = file_put_contents($file, "Spade\n");
    if ($written !== 6) throw new RuntimeException("Incomplete first write");
    file_put_contents($file, "Rake\n", FILE_APPEND);
    echo file_get_contents($file);
} finally { unlink($file); }

Expected result

Spade
Rake

The first write stores six bytes including the newline. The append adds another line without replacing the first. Byte counts are not character counts in an arbitrary encoding. The final read verifies the stored sequence, but this small test does not establish crash-safe or concurrent append guarantees for every filesystem.

Check the official PHP manual for detailed version and API contracts.