Question

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/.......

Was it helpful?

Solution 2

The constants that Cake generates (or hands you over...) are documented in the Global Constants and Functions.

Using Cake's global APP seems the way to go (unless you don't want to move the files in the APP/ folder).

OTHER TIPS

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);

You could use php function getcwd() to get the base dir of your app.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top