Monday, February 9, 2009

Php - File writer class - write files and take its backups so that it can be easily reverted

File Writer is a simple class designed to make writing files, or appending to files, much easier. It also has optional functionality to take backups of files it writes to so that changes can be reverted easily.

Usage: Example


<?PHP
//Include the main class file
include("main.php");

//Create a new file_writer object
$file = new file_writer;

//Write to a new file
$file->write("test.txt", "Test Test Test");

//Append more text to the file
$file->append("test.txt", "\r\nTest Test Test");
?>

main.php

<?PHP
//Should file_writer take backups of files
define("WRITER_BACKUP", TRUE);
 
//Where should file_writer store backups
define("WRITER_RESTORE_DIR", "./restore");
 
//Should file_writer lock files while writing to them
define("WRITER_LOCK_FILES", TRUE);
 
class file_writer
    {
    public $files = array();
    
    function __construct()
        {
        
        }
        
    function write($file, $content)
        {
        $date = date("d-m-Y_his");
        //Copy the original file to the restore dir
        if(file_exists($file))
            {
            if(WRITER_BACKUP)
                {
                copy($file, WRITER_RESTORE_DIR."/".$date."_".$file);
                }
            }
            
        if(!isset($files[$file]))
            {    
            //Make the file handle
            $files[$file] = fopen($file, "w");
            if(WRITER_LOCK_FILES)
                {
                flock($files[$file], LOCK_EX);
                }
            }
            
        //Overwrite the file
        fwrite($files[$file], $content);
        }
        
    function append($file, $content)
        {
        $date = date("d-m-Y_his");
        //Copy the original file to the restore dir
        if(file_exists($file))
            {
            if(WRITER_BACKUP)
                {
                copy($file, WRITER_RESTORE_DIR."/".$date."_".$file);
                }
            }
        
        if(!isset($files[$file]))
            {    
            //Make the file handle
            $files[$file] = fopen($file, "a");
            if(WRITER_LOCK_FILES)
                {
                flock($files[$file], LOCK_EX);
                }
            }
            
        //Overwrite the file
        fwrite($files[$file], $content);
        }
        
    function __destruct()
        {
        foreach($this->files as $file)
            {
            fclose($file);
            }
        if(WRITER_LOCK_FILES)
            {
            foreach($this->files as $file)
                {
                flock($file, LOCK_EX);
                }
            }
        }
    }
 
?>


No comments: