Home >> Snippet List >> Snippet

Name
Write to File example
Description
A quick example of writing to a flat file
PHP Snippet
<?PHP 
 
$filename = 'test.txt'; 
$somecontent = "Add this text to the file\n"; 
 
// Let's make sure the file exists and is writable first. 
IF (IS_WRITABLE($filename)) { 
 
    // In our example we're opening $filename in append mode. 
    // The file pointer is at the bottom of the file hence 
    // that's where $somecontent will go when we fwrite() it. 
    IF (!$handle = FOPEN($filename, 'a')) { 
         PRINT "Cannot open file ($filename)"; 
         EXIT; 
    } 
 
    // Write $somecontent to our opened file. 
    IF (!FWRITE($handle, $somecontent)) { 
        PRINT "Cannot write to file ($filename)"; 
        EXIT; 
    } 
 
    PRINT "Success, wrote ($somecontent) to file ($filename)"; 
 
    FCLOSE($handle); 
 
} ELSE { 
    PRINT "The file $filename is not writable"; 
} 
?>