php - CakePHP: validation of form upload field if file exists not working -



php - CakePHP: validation of form upload field if file exists not working -

cakephp 2.x: struggling validating image upload field in form adding users. upload field not manditory. validates field false while image uploaded. seems whole validation working partially. help appreciated

user.php model :

public $validate = array( 'picture' => array( 'required' => false, 'allowempty' => true, 'custom' => array( 'rule' => array('imageexist'), 'message' => 'there image name on server' ) )); // function check if file exists public function imageexist($check) { $picturename = $check['picture']; $path = www_root . 'userimages/'; $file = $path . $picturename; if (file_exists($file)) { homecoming false; } else { homecoming true; } }

add.ctp:

<?php echo $this->form->create('user', array('class' => 'form-horizontal', 'role' => 'form', 'div' => false, 'type' => 'file')); echo $this->form->input('username', array('label' => "username")); echo $this->form->input('picture', array('label' => "avatar", 'type' => 'file')); echo $this->form>formdefaultactions(); echo $this->form->end(); ?>

usercontroller.php:

public function add() { if ($this->request->is('post')) { $this->user->create(); // set image , path $filedir = www_root . 'userimages/'; $file = $filedir . $this->request->data['user']['picture']['name']; // upload avatar image move_uploaded_file( $this->request->data['user']['picture']['tmp_name'], $file ); $this->request->data['user']['picture'] = $this->request->data['user']['picture']['name']; if ($this->user->save($this->request->data)) { $this->session->setflash(__('the user has been added'), 'success' ); $this->redirect(array( 'action' => 'index' )); } else { $this->session->setflash(__('the user not created. please, seek again'), 'error' ); } } }

you need check validation before uploading or false. if upload file, when cakephp validates file exists in folder.

you can move logic like:

$this->request->data['user']['picture'] = $this->request->data['user']['picture']['name']; if ($this->user->save($this->request->data)) { move_uploaded_file( $this->request->data['user']['picture']['tmp_name'], $file ); }

or check, before saving:

if ($this->user->validates()) { if ($this->user->save($this->request->data)) { move_uploaded_file( $this->request->data['user']['picture']['tmp_name'], $file ); } }

php validation cakephp

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -