Writing Files in PHP

Here’s the translated code and explanation in PHP, formatted in Markdown suitable for Hugo:

Writing files in PHP follows similar patterns to the ones we saw earlier for reading.

<?php

function check($e) {
    if ($e !== null) {
        throw new Exception($e);
    }
}

// To start, here's how to dump a string (or just bytes) into a file.
$d1 = "hello\nphp\n";
$err = file_put_contents("/tmp/dat1", $d1, LOCK_EX);
check($err === false ? "Failed to write to file" : null);

// For more granular writes, open a file for writing.
$f = fopen("/tmp/dat2", "w");
check($f === false ? "Failed to open file" : null);

// It's a good practice to close the file handle when we're done.
register_shutdown_function(function() use ($f) {
    fclose($f);
});

// You can write strings as you'd expect.
$d2 = "some\n";
$n2 = fwrite($f, $d2);
check($n2 === false ? "Failed to write to file" : null);
echo "wrote " . strlen($d2) . " bytes\n";

// Another write example
$n3 = fwrite($f, "writes\n");
check($n3 === false ? "Failed to write to file" : null);
echo "wrote $n3 bytes\n";

// Flush writes to ensure they're written to disk
fflush($f);

// PHP doesn't have a built-in buffered writer, but we can create a simple one
class BufferedWriter {
    private $handle;
    private $buffer = '';
    
    public function __construct($handle) {
        $this->handle = $handle;
    }
    
    public function write($string) {
        $this->buffer .= $string;
        return strlen($string);
    }
    
    public function flush() {
        $result = fwrite($this->handle, $this->buffer);
        $this->buffer = '';
        return $result;
    }
}

$w = new BufferedWriter($f);
$n4 = $w->write("buffered\n");
echo "wrote $n4 bytes\n";

// Use flush to ensure all buffered operations have been applied to the underlying writer.
$w->flush();

?>

Try running the file-writing code.

$ php writing-files.php 
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

Then check the contents of the written files.

$ cat /tmp/dat1
hello
php
$ cat /tmp/dat2
some
writes
buffered

Next we’ll look at applying some of the file I/O ideas we’ve just seen to the stdin and stdout streams.