FileTools Class

From Superk

Jump to: navigation, search
<?php
class fileTools
{
  /**
   * fileTools::fileHandler - Handles uploaded files
   *
   */
  function fileHandler($file, $type, $updir)
  {
    if($file['error'] > 0) {
      echo $this->fileError($file['error']);
    } elseif($this->fileMime($file['type'], $type) > 0) {
      echo "Error: File type not allowed or supported.";
    } elseif($this->fileMove($file['tmp_name'], $updir) > 0) {
      if($this->fileMove($file['tmp_name'], $updir) == 1) {
	echo "Error: File could not be moved to the destination directory.";
      } else {
	echo "Error: Possible file upload attack.";
      }
    } else {
      return true;
    }
  }

  /**
   * fileTools::fileError - Evaluates file error codes
   *
   * Interprets the uploaded file's error attribute and returns friendly
   * errors.
   *
   * @param string $error File's Error attribute
   * @author
   */
  function fileError($error)
  {
    if($file > 0) {
      $out = "Error: ";
      switch($file) {
	case 1: $out .= "File exceeded PHP upload limit."; break;
	case 2: $out .= "File exceeded author's upload limit."; break;
	case 3: $out .= "File only partially uploaded."; break;
	case 4: $out .= "No file uploaded."; break;
      }
      return $out;
    }
    return 0;
  }
	
  /**
   * fileTools::fileMime - Evaluates the MIME type
   *
   * Examines the uploaded file's MIME type and determines if it matches
   * one of the accepted formats for this particular data type.
   *
   * @param string $file File's MIME attribute
   * @param string $type Do appropriate validation based on expected type
   * @author
   */
  function fileMime($filetype, $type)
  {
    if($type == 'photo') {
      if($filetype != ('image/jpeg' || 'image/tiff' || 'image/x-png' || 'image/gif')) {
	return 1;
      }
    } elseif($type == 'doc') {
      if($filetype != ('application/pdf' || 'application/rtf' || 'text/html' || 'text/plain')) {
	return 1;
      }
    }
    return 0;
  }
	
  /**
   * fileTools::fileMove - Moves the file to the upload directory
   *
   * Private method for moving the uploaded file to the given destination
   * directory.
   *
   * @param string $file File to move from tmp to destination
   * @param string $up Destination directory to move file to
   * @author
   */
  function fileMove($file, $up)
  {
    if(is_uploaded_file($file)) {
      if(!move_uploaded_file($file, $up)) {
	return 1;
      }
      return 0;
    } else {
      return 1;
    }
  }
	
} // Close class block
?>
Personal tools