image upload in cake 2 code example
Example 1: image upload in cake 2
public function add() {
if ($this->request->is('post')) {
$this->Category->create();
if (!empty($this->request->data['Category']['upload']['name'])) {
$file = $this->request->data['Category']['upload'];
$ext = substr(strtolower(strrchr($file['name'], '.')), 1);
$arr_ext = array('jpg', 'jpeg', 'gif','png');
if (in_array($ext, $arr_ext)) {
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/webimages/categories/' . $file['name']);
$this->request->data['Category']['image'] = $file['name'];
}
}
if ($this->Category->save($this->request->data)) {
$this->Session->setFlash(__('The category has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The category could not be saved. Please, try again.'));
}
}
$parentCategories = $this->Category->ParentCategory->find('list');
$categoriesStatus = $this->Category->getCategoriesStatus();
$this->set(compact('parentCategories', 'categoriesStatus'));
}
Example 2: image upload in cake 2
public function add() {
if ($this->request->is('post')) {
$this->Product->create();
if ($this->Product->save($this->request->data)) {
$this->Session->setFlash(__('The product has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The product could not be saved. Please, try again.'));
}
if(!empty($this->data))
{
if(!empty($this->data['products']['upload']['name']))
{
$file = $this->data['products']['upload'];
$ext = substr(strtolower(strrchr($file['name'], '.')), 1);
$arr_ext = array('jpg', 'jpeg', 'gif');
if(in_array($ext, $arr_ext))
{
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'CakePHP/app/webroot/img/' . $file['name']);
$this->data['products']['product_image'] = $file['name'];
}
}
$this->products->save($this->data) ;
}
}
}