Rev 7 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed
<?php
/*
* Wrapper for file functions. Ensures the path to the file is available
* then opens the file (default append/binary mode) and grabs an
* exclusive lock
*/
class File {
// fully qualified path and file name
protected $fullFileName;
// file name
protected $filename;
// path to file
protected $path;
// permissions to assign to path
protected $pathPermission = 0777;
// mode to open in. Default is append in binary mode
public $filemode = 'ab';
// file handle
protected $fh = null;
/*
* constructor must have file name, all else is default
* however filename may be empty or null
*/
public function __construct( $filename = null, $filemode = null ) {
//if ( $filemode !== null ) $this->filemode = $filemode;
if ( isset( $filename ) && $filename ) {
$temp = pathinfo( $filename );
$this->filename = $temp['basename'];
$this->path = $temp['dirname'];
$this->fullFileName = $this->path . '/' . $this->filename;
$this->makePath(); // will return false if we could not create the path
}
$this->openFile();
} // __construct
public function openFile() {
if ( ! isset( $fh ) && isset( $this->fullFileName ) ) {
$this->fh = fopen( $this->fullFileName, $this->filemode );
/*if ( $this->fh === false )
die( "could not write to $this->fullFileName" );
// get exclusive lock during script life.
if ( ! flock( $this->fh, LOCK_EX ) )
die( "could not acquire lock on $this->fullFileName" );
*/
}
}
public function closeFile () {
if ( isset( $this->fp) ) fclose( $this->fp );
}
/*
* creates path $path if it does not exist
* sets permissions to $pathPermission
* Note: this does a recursive creation (mkdir -p) but does not
* check permissions on existing directories
* returns true on success, false on failure
*/
private function makePath() {
/* we'll return true if the path exists. HOWEVER, note that
* we do not check permissions, so this could cause issues
*/
if ( is_dir( $this->path ) )
return true;
/* path does not exist. Save the current umask and set it
* temporarily to 0, then create the directory and restore
* umask
*/
$oldmask = umask(0); // set umask to 0 temporarily
$result = mkdir( $this->path, $this->pathPermission, true ); // recursively build tree
umask( $oldmask ); // restore umask
return $result;
} // makePath
} // class file
?>