Getting base directory in CakePHP

user2387319 picture user2387319 · Aug 5, 2013 · Viewed 16.8k times · Source

I am working on a CakePHP project. Here, I have to upload a file and then move that file to a specific folder. Uploading is working well, but I can't move it to the folder I want. Is there any function or something in CakePHP to move the uploaded file ?

Currently I am using PHP's core function move_uploaded_file(). This function requires absolute path for both source & destination, not the http://localhost/...., I tried it, but it didn't work. So, do you know how do I get the Base Directory/Absolute Path of my application ? This would be like : C://wamp/www/project_folder/.......

Answer

Ketan picture Ketan · Aug 6, 2013

Add function in Controller

public function add() {
    $this->Model->create();
    if ($this->request->is('post')) {
        if(!empty($this->data['Model']['image']['name']))
        {
        $file=$this->data['Model']['image'];
        $ary_ext=array('jpg','jpeg','gif','png');
        $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
            if(in_array($ext, $ary_ext))
            {
                move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/uploads/posts/' . $file['name']);
                $this->request->data['Model']['image'] = $file['name'];
            }   
        }
        if ($this->Model->save($this->request->data)) 
        {
            $this->Session->setFlash('Your record has been saved.');
            $this->redirect(array('action' => 'index'));
        }
        else 
        {
            $this->Session->setFlash('Unable to add your record.');
        }
    }
}


File control in add.ctp file

echo $this->Form->input('image',array('type'=>'file'));


you can define constant in index.php file like below
/**
 *  Get Cake's root directory
 */
define('APP_DIR', 'app');
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', dirname(__FILE__));
define('WEBROOT_DIR', 'webroot');
define('WWW_ROOT', ROOT . DS . APP_DIR . DS . WEBROOT_DIR . DS);