Enterprise System Developer

Upload Component in CakePHP 2.X

Tweet about this on TwitterShare on FacebookShare on LinkedInShare on Google+Email this to someonePrint this page

Creating Component

Start with declear a Component :

class UploadComponent extends Component {

Define some variables

    var $method = '';
    var $name = 'Upload';

    var $_file;
    var $_filepath;
    var $_destination;
    var $_name;
    var $_short;
    var $errors;

Define exteneion to allow uplaod them

var $_ext = array (
                'image' => array ('jpg', 'png', 'gif', 'jpeg'),
                'document' => array ('pdf', 'doc', 'docx', 'txt', 'rtf'),
                'video' => array ('flv', ),
                'compress' => array('zip'),
                'html' => array('js', 'html'),
                );

Assigns values of referencing controller

function startup(Controller $controller) {
    $this->name = $controller->name;
}

function upload here

function upload ($file, $destination, $type = 'image', $name = NULL) {
    $this->result = false;
    $this->error = false;

    // -- save parameters
    $this->_file = $file;
    $this->_destination = $destination;

    // -- hack dir if / not provided
    if (substr($this->_destination,-1) != '/') {
        $this->_destination .= '/';
    }

    // -- check that FILE array is even set
    if (isset($file) && is_array($file) && !$this->upload_error($file['error'])) {

        // -- cool, now set some variables
        $fileName = ($name == NULL) ? $this->uniquename($destination . $file['name']) : $destination . $name;
        $fileTmp = $file['tmp_name'];
        $fileSize = $file['size'];
        $fileType = $file['type'];
        $fileError = $file['error'];

        // Check is file Allowed
        $ext = $this->ext ($file['name']);
        if (!in_array($ext, $this->_ext[$type])) {
            $this->error("Extention '$ext' NOT Allowed");
            return false;
        }

        // -- update name
        $this->_name = $fileName;
        // -- it's been uploaded with php
        if (is_uploaded_file($fileTmp)) {
            $output = $fileName;
            // -- just upload it
            if (move_uploaded_file($fileTmp, $output)) {
                chmod($output, 0644);
                $this->result = basename($this->_name);
                return true;
            } else {
                $this->error("Could not move '$fileName' to '$destination'");
            }
        } else {
            $this->error("Possible file upload attack on '$fileName'");
        }

    } else {
        $this->error("Possible file upload attack");
    }
}

function to Check is file Allowed

function ext ($file) {
    $ext = trim(substr($file,strrpos($file,".")+1,strlen($file)));
    $ext = strtolower($ext);;
    return $ext;
}

function error message

function error ($message){
    if (!is_array($this->errors)) $this->errors = array();
    array_push($this->errors, $message);
}

Set new name to file uploaded

function newname ($file) {
    return time() . "." . $this->ext($file);
}

 

Set unique name

function uniquename ($file) {
    $parts = pathinfo($file);
    $dir = $parts['dirname'];
    $file = ereg_replace('[^[:alnum:]_.-]','',$parts['basename']);
    $ext = $parts['extension'];
    if ($ext) {
        $ext = '.'.$ext;
        $file = substr($file,0,-strlen($ext));
    }
    $i = 0;
    while (file_exists($dir.'/'.$file.$i.$ext)) $i++;
        return $dir.'/'.$file.$i.$ext;
}

 

Error messages

function upload_error ($errorobj) {
    $error = false;
    switch ($errorobj) {
       case UPLOAD_ERR_OK: break;
       case UPLOAD_ERR_INI_SIZE: $error = "The uploaded file exceeds the upload_max_filesize directive (".ini_get("upload_max_filesize").") in php.ini."; break;
       case UPLOAD_ERR_FORM_SIZE: $error = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form."; break;
       case UPLOAD_ERR_PARTIAL: $error = "The uploaded file was only partially uploaded."; break;
       case UPLOAD_ERR_NO_FILE: $error = "No file was uploaded."; break;
       case UPLOAD_ERR_NO_TMP_DIR: $error = "Missing a temporary folder."; break;
       case UPLOAD_ERR_CANT_WRITE: $error = "Failed to write file to disk"; break;
       default: $error = "Unknown File Error";
    }
    return ($error);
}

 

and close class

}

 

How can use it in controller :

after get file from post form

//check file there is no error and file size bigger than 0 byte

if ($this->data['Item']['filename']['error'] == 0 && $this->data['Item']['filename']['size'] > 0){
    // pathes to upload
    $path = WWW_ROOT . 'upload' . DS . 'files' . DS ;
    //set new name to uplaoded file
    $NewFileName = $this->Upload->newname($this->data['Item']['filename']['name']);
    // upload file to path
    // here in parameter "image" you can change it that if you want to upload another extension
    if ($this->Upload->upload($this->data['Item']['filename'], $path, 'image', $NewFileName)){
        //set new file name to variable to save it
        $thumb = $NewFileName;
    }
    else{
        //set log error if there is problem in uploading
        $this->log(print ('Uploading Error in File'));
    }
}
Tweet about this on TwitterShare on FacebookShare on LinkedInShare on Google+Email this to someonePrint this page

One Response

  1. Yor says:

    Hi,
    Could you tell me what the view is like for this example.
    The .ctp
    Session->flash();
    echo $this->Form->create(‘Item’, array(‘type’ => ‘file’));
    echo $this->Form->input(‘file’,array( ‘type’ => ‘file’));
    echo $this->Form->end(‘Submit’);
    ?>

Comments

Your email address will not be published. Required fields are marked *