CPSC415A
Web Programming

Day 13 Notes

PHP File I/O

Reading

$file = fopen($filename, 'r');
if (flock($file, LOCK_SH)) {
    echo fread($file, filesize('useless.txt'));
    flock($file, LOCK_UN);
    fclose($file);
}
$file = fopen($filename, 'r');
if (flock($file, LOCK_SH)) {
    while (!feof($file)) {
        echo fgets($file) . '<br />';
    }
    flock($file, LOCK_UN);
    fclose($file);
}

Writing

// NOTE: Need to give the server write access to the file.
//       Use chmod from the command line to change the file permissions.
$file = fopen($filename, 'a'); // using w erases on open
if (flock($file, LOCK_EX)) {
    ftruncate($file, 0); // erase the file contents when writing below
    fwrite($file, $stuffToWrite);
    fclose($file);
    fflock($file, LOCK_UN);
}