Location: PHPKode > scripts > ImageUpload > imageupload/imageUpload.class.php
<?php

/*
 created by Steve Krishna
 08-03-2009

*/

class imageUpload {

    public $error = NULL;

    private $max_size = 1000000;        //max file size allowed - default 1024
    private $upload_dir = 'uploaded_files/';    //Destination Directory - default document root/uploaded_files

    private $tn_create = true;          //IF to create thumnail or not(True/False) - default True
    private $tn_size = 150;             //thumbnail maximum size
    private $tn_name = 'tb_';           //thumbnail image name - default tb_ + filename
   
     
    private $file;          //file upload object
    private $file_name;     //file name
    private $file_size;     //file size
    private $file_tmp;      //temporary file name created by file upload
    private $file_type;     //file type with mime type
    private $file_ext;      //file extension 


    private $image_info;    //to get image information
    private $thumb;         //created thumbnail

    private $image_ext_allowed = array('jpg', 'jpeg', 'png', 'gif','bmp');
    private $doc_ext_allowed = array('doc', 'txt', 'pdf');

    //Error messages for #6, #7 and #8 (Use for debugging purposes)
    // #6 - One or more parameter(s) missing
    // #7 - Directory not found and/or cannot create
    // #8 - Cannot create thumbnail

    private $errmsg = array(1=> 'Image/File upload failed',
                2=> 'Cannot create thumbnail',
                3=> 'Error copying file',
                4=> 'The file/image size is too big. Cannot upload',
                5=> 'File type not supported',
                6=> '6',
                7=> '7',
                8=> '8');


    //constructor - input values as array
    public function __construct($opts) 
    {
        //Check and assign variables passed by calling page. Variable File is important!
        foreach ($opts as $key=>$val){
                 $this->$key = $val;

        }

        //Get file information into variables
        if($this->file){
           $this->file_name = $_FILES[$this->file]['name'];
           $this->file_size = $_FILES[$this->file]['size'];
           $this->file_tmp  = $_FILES[$this->file]['tmp_name'];
           $this->file_type = $_FILES[$this->file]['type'];
           $this->file_ext  = pathinfo($this->file_name, PATHINFO_EXTENSION);
           
           //Check file size against max file size
           if(!($this->checkFileSize())){ return false; }

           //Check file type image or document
           if(!($this->checkFileType())){ return false;}

        }else{
               $this->error = $this->errmsg[6];
               return false;
        }
    }

    //check file size method
    private function checkFileSize(){

        //Check file size
        if((is_numeric($this->file_size)) && ($this->file_size <= $this->max_size)){
             return true;
        } else {
                 $this->error = $this->errmsg[4];
                 return false;
        }
    }

    //Check file type and continue with upload
    private function checkFileType(){

       //echo  $this->doc_ext_allowed[1];
        if($this->in_arrayi(strtolower($this->file_ext), $this->image_ext_allowed)){     //Check if it's supported image file

             //If supported image type create thumbnail if needed
             $this->image_info = getimagesize($this->file_tmp);
             $this->createThumb();

             //Copy Original file to directory
             if(!($this->copyFile())){ return false;}
             return true;

        }elseif($this->in_arrayi(strtolower($this->file_ext), $this->doc_ext_allowed)){       //Check if it's supported document file
              //Copy Original file to directory
             if(!($this->copyFile())){ return false;}
             return true;
        }else{
             $this->error = $this->errmsg[5];
             return false;
        }
    }

    private function copyFile(){

        if($this->checkDirectory()){  //Check directory before copying
           //$this-> deleteExisting();  //Delete if file exist;

           if(!(move_uploaded_file($this->file_tmp, $this->upload_dir.''.$this->file_name))){
                $this->error = $this->errmsg[3];
                return false;
           }else{
                  return true;
           }
        }else{
              return false;
        }
    }

    private function checkDirectory(){

        //check to see if the directory exists and create it if necessary
        if (!is_dir($this->upload_dir))
        {
           if(!(mkdir($this->upload_dir, 0777))){
              $this->error = $this->errmsg[7];
              return false;
           }else{
               return true;
           }
        }else{
          return true;
        }
    }

    //Delete existing file/image if exist
    private function deleteExisting() 
    { 
        //Check for the origanl file
        $o_file =  $this->upload_dir.''.$this->file_name;
        if(file_exists($o_file)) unlink($o_file);

        //Ceheck for thumbnail
        $o_file =  $this->upload_dir.''.$this->tn_name.''.$this->file_name;
        if(file_exists($o_file)) unlink($o_file);
    }



    private function createThumb(){

            if($this->tn_create){

                $width  = isset($this->image_info['width'])  ? $this->image_info['width']  : $this->image_info[0];        
                $height = isset($this->image_info['height']) ? $this->image_info['height'] : $this->image_info[1];

                // Calculate aspect ratio        
                $wRatio = $this->tn_size / $width;
                $hRatio = $this->tn_size / $height;

                // Using imagecreatefromstring will automatically detect the file type
                $sourceImage = imagecreatefromstring(file_get_contents($this->file_tmp));

                // Calculate a proportional width and height no larger than the max size.
                if (($width <= $this->tn_size) && ($height <= $this->tn_size)){
                     // Input is smaller than thumbnail, do nothing
                     $tn_width = $width;
                     $tn_height = $height;
                }elseif(($wRatio * $height) < $this->tn_size){
                        // Image is horizontal
                        $tn_height = ceil($wRatio * $height);
                        $tn_width  = $this->tn_size;
                }else{
                       // Image is vertical
                       $tn_width  = ceil($hRatio * $width);
                       $tn_height = $this->tn_size;
                }

                //echo $width.'  '.$height.'  '.$wRatio.'  '.$hRatio.'  '.$tn_height.'  '.$tn_width;
                $this->thumb = imagecreatetruecolor($tn_width, $tn_height);

                imagecopyresampled($this->thumb, $sourceImage, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
                imagedestroy($sourceImage);
                $this->copyThumb();   //copy thumnail to directory

            }
    }

    private function copyThumb(){

            if(isset($this->thumb)){
              //Copy thumbnail
              switch(strtolower($this->file_ext))
              {
                      case 'jpg':          //J-Peg images
                      case 'jpeg': 
                      case 'pjpeg': 
                           imagejpeg($this->thumb, $this->upload_dir.''.$this->tn_name.''.$this->file_name);
                           break;

                      case 'png':          //PNG images
                      case 'x-png': 
                           imagepng($this->thumb, $this->upload_dir.''.$this->tn_name.''.$this->file_name);
                           break; 

                      case 'gif':          //GIF images
                           imagegif($this->thumb, $this->upload_dir.''.$this->tn_name.''.$this->file_name);
                           break; 

                      case 'bmp':          //BMP images
                      case 'wbmp': 
                           imagewbmp($this->thumb, $this->upload_dir.''.$this->tn_name.''.$this->file_name);
                           break; 

                      default:             //Other files - fail upload!
                          $this->error = $this->errmsg[2];
                          return false;
                          break;
              }
            }

    }

    //Since in_array() function gave lot of error i created my own
    private function in_arrayi( $needle, $haystack ) {
        $found = false; 
        foreach( $haystack as $value ) { 
            if( strtolower( $value ) == strtolower( $needle ) ) { 
                $found = true; 
            } 
        }    
        return $found; 
    }
}
?>



Return current item: ImageUpload