Return to Snippet

Revision: 38596
at January 5, 2011 16:45 by asdasDan


Initial Code
<?php

class fileManipulation
{
	protected $__workingFile   = NULL;
	protected $_workingHandle  = NULL;
    protected $_workingMode    = NULL;
	protected $_handleExists   = FALSE;


	function __construct($fileName)
	{
		// Error out if the file is a directory, or doesn't exist
		if ((!@file_exists($fileName)) || (@is_dir($fileName)))
		{
			exit("File does not exist, or is a directory.");
		} else {
			$this->_workingFile = $fileName;
		}
	}
	
	/* ####################### FILE INFORMATION ####################### */
        /**
         *
         * @return string Name of file that the user is working with.
         */
        function getFile()
        {
            return $this->_workingFile;
        }

        /**
         * Allows the end user to retrieve specific information about the working file.
         *
         * @return array Associative array of specific file information.
         */
	function information()
	{
		// Raw filesize followed by MB (Hundreths placement)
		$fileSize   = @filesize($this->_workingFile);
		$fileSizeMB = @round($fileSize/1048576, 2);
		
		// Use stat() to retrieve basic access info
		$statInfo     = @stat($this->_workingFile);
		$lastAccess   = $statInfo['atime'];
		$lastModified = $statInfo['mtime'];
		
		// Retrieve complex permission values
		$complexPermissions = @fileperms($this->_workingFile);
		// Retrieve last 3 complex file permission values (ie 777 or 644)
		$simplePermissions  = @substr(decoct($complexPermissions), 3);
		// Convert complex permissions to rw-r.. format
		$ufPermissions      = $this->_advancedPerms($complexPermissions);
		
		// Simple file permissions
		$isReadable = @is_readable($this->_workingFile);
			## -- Note: is_writable() handles errors with an E_WARNING, so set value to 0(False) upon failure
		$isWritable = (@is_writable($this->_workingFile)!=1) ? 0 : 1;
		
		// Return associative array to obtain singled out information
		return array(
				"fileSize"     => $fileSizeMB,
				"lastAccess"   => $lastAccess,
				"lastModified" => $lastModified,
				"complexPerms" => $complexPermissions,
				"simplePerms"  => $simplePermissions,
				"ufPerms"      => $ufPermissions,
				"isReadable"   => $isReadable,
				"isWritable"   => $isWritable);		
	}

        /**
         * Takes a complex permission string and turns it into a symbolic
         * notation, protected since it's only available to the information() function.
         *
         * @param int $permString A string of permissions in the format of: 33206
         * @return string A string in the format of -rw-r--r--
         */
	protected function _advancedPerms($permString)
	{
		if (($permString & 0xC000) == 0xC000)
		{
			$notation = "s"; // Socket 
		} elseif (($permString & 0xA000) == 0xA000)
		{
			$notation = "l"; // Symbolic Link
		} elseif (($permString & 0x8000) == 0x8000)
		{
			$notation = "-"; // Regular
		} elseif (($permString & 0x6000) == 0x6000)
		{
			$notation = "b"; // Block special
		} elseif (($permString & 0x4000) == 0x4000)
		{
			$notation = "d"; // Directory
		} elseif (($permString & 0x2000) == 0x2000)
		{
			$notation = "c"; // Character special
		} elseif (($permString & 0x1000) == 0x1000)
		{
			$notation = "p"; // FIFO pipe
		} else {
			$notation = "u"; // Unknown
		}



		// Owner
		$notation .= (($permString & 0x0100) ? 'r' : '-');
		$notation .= (($permString & 0x0080) ? 'w' : '-');
		$notation .= (($permString & 0x0040) ? (($permString & 0x0800) ? 's' : 'x' ) : (($permString & 0x0800) ? 'S' : '-'));

		// Group
		$notation .= (($permString & 0x0020) ? 'r' : '-');
		$notation .= (($permString & 0x0010) ? 'w' : '-');
		$notation .= (($permString & 0x0008) ? (($permString & 0x0400) ? 's' : 'x' ) : (($permString & 0x0400) ? 'S' : '-'));

		// World
		$notation .= (($permString & 0x0004) ? 'r' : '-');
		$notation .= (($permString & 0x0002) ? 'w' : '-');
		$notation .= (($permString & 0x0001) ? (($permString & 0x0200) ? 't' : 'x' ) : (($permString & 0x0200) ? 'T' : '-'));

		return $notation;		
	}
	/* ####################### FILE INFORMATION ####################### */
	
	
	/* ####################### FILE MODIFICATIONS ####################### */
	function newMode($newMode)
	{
		// decoct makes 0777, 777, etc
		return (@chmod($this->_workingFile, decoct($newMode)));
	}
	
	function hardCopy($newName) // hardCopy overwrites files that exist
	{
		return @copy($this->_workingFile, $newName);
	}
	
	function softCopy($newName) // if file exists dont copy, otherwise copy
	{
		return (@file_exists($newName)) ? FALSE : (@copy($this->_workingFile, $newName));
	}
	
	function newName($newName)
	{
		return @rename($this->_workingFile, $newName);
	}
	
	function remove()
	{
		return unlink($this->_workingFile);
	}
	/* ####################### FILE MODIFICATIONS ####################### */

        /**
         * Allows for a manual method of setting the fopen handle, with an optional
         * parameter of setting the write mode to something other than a+.
         *
         * @param string $writeMode What mode the user wants to open the file with.
         * @return NONE
         */
	function setHandle($writeMode="a+")
	{
		$this->_workingHandle = @fopen($this->_workingFile, $writeMode);
        $this->_workingMode   = $writeMode;
		$this->_handleExists  = ($this->_workingHandle) ? TRUE : FALSE;
        return;
	}

	/**
         *
         * @param string $preText Text to display before the reading of the file.
         * @return string Contents of file being read with fread()
         */
	function read($preText=NULL)
	{
		if (!$this->_handleExists)
		{
			$this->setHandle();
		}
		
		return $preText."<br />".fread($this->_workingHandle, filesize($this->_workingFile));
	}

        /**
         *
         * @param string/array $data Whatever information desired to be written to the working file.
         * @return NONE
         */
	function write($data)
	{
            if ($this->_workingMode=="r")
            {
                die("Invalid mode for writing. <br /><strong>Mode Specified: \"".$this->_workingMode."\"</strong>");
            }
			
			if (!$this->_handleExists)
			{
				$this->setHandle();
			}

            @fwrite($this->_workingHandle, $data);
            return;

	}
	
        /**
         * Read a file out into an array without requiring a handle such as fopen,
         * it uses the file function.
         *
         * @param int $limit Limit the amount of lines you want to be returned in the array
         * @return array An array of elements including each individual line
         */
	function lineByLine($limit=0)
	{
		// Setup the array of each line, and a count of total lines
		$arrayOfLines = file($this->_workingFile);
		$lineCount = count($arrayOfLines);
		
		// If the user set a limit on how many lines they want returned
		if ($limit!=0)
		{
			// Loop through and unset the last element of the array
			// until it is to the desired line limit
			for ($i=$lineCount; $i>$limit; $i--)
			{
				unset($arrayOfLines[$i]);
			}
		}
			
		return $arrayOfLines;
	}
	
	function __destruct()
	{
		// If any handles exist, ie - a file was opened
		// and not closed, we close it now
		if ($this->_handleExists)
                {
                    fclose($this->_workingHandle);
        	}
	}
	
}

Initial URL

                                

Initial Description
This was more of a go at learning the basics of OOP, however I decided to document it well in case anyone had any comments. Note: It only works with single files, no directory usage.

Initial Title
File Manipulation/Information

Initial Tags
file, copy

Initial Language
PHP