Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 934
  • Last Modified:

Cakephp Validation not working

Hi all,

I have added some validation to my model but it just won't work. I wonder what might be going wrong. No messages are shown either.

Code is below attached:

Hope someone can help

THanks

//Model Code

<?php
class Upload extends AppModel {
var $name = 'Upload';
var $useTable = 'entries';

var $validate = array(
        'name' => array(
            'rule' => 'alphaNumericDashUnderscore',
            'allowEmpty' => false,
            'message' => 'Only letters, numbers, dash and underscore'
        ),
        'upload' => array(
            'rule' => array('extension',array('jpg','gif','jpeg','tif','png','mov','mp4','flv','swf')),
            'required' => true,
            'allowEmpty' => false,
            'message' => 'Invalid file'
        ),
		'file' => array(
		'rule' => array('validateFile', true),
		'allowEmpty' => false,
		'message' => 'There is a problem with uploading the file.' //message
)
		
       );



function validateFile($data, $required = false) {
$file = array_shift($data); // for easier handling

if ($required && $file['size'] == 0) {
	
	echo 'This file is invalid or empty!';
	
}
 // If no file is uploaded
if ($file['error'] !== 0) return false; // PHP Errors 
if ($upload_info[‘error’] !== 0) {	return false; }
return is_uploaded_file($file['tmp_name']); // If everything is fine

}
}
?>

//controller code

<?php
class UploadsController extends AppController {
	
	var $name = 'Uploads';
	var $useTable = 'competitions_entry';
	var $components = array('RequestHandler','FileUpload','Session');  
	var $helpers = array('Html', 'Form', 'Javascript','Session', 'Ajax');
	var $uses = array('User','Competition','Upload', 'Vote');
	
		
	
	
	
	function index($id = null) {
		

		
		//$this->set('uploads', $this->Upload->find('all')); 
		
		$theuploads = $this->Upload->query("SELECT * FROM entries");
										   
		$this->set('uploads', $theuploads);
		
			
		if($this->RequestHandler->isPost()) {
		
		
		
		$this->Upload->create();
		
			$component = new FileUploadComponent();
			$component->upload(array('name'=>'blablabla', 'tmp_name'=>'tmp_blabla'));
			$FullUrl = $component->getFullpath();
			$currentUserId = $this->sodium_user['User']['id'];
			$test = $component->getFolder();
			
		
				
		
		   
			//Get the path to save;
			$data = array('Upload' => array(
					'competition_id' => $this->data['Upload']['comp_id'],
					'user_id' => $currentUserId,// <- Need to get this via url
			 		'directory_name'=> 'img/uploads/',
					'name' => $test.'-'.$this->data['Upload'][0]['file']['name'],
					'size' => $this->data['Upload'][0]['file']['size'], 
					'type' => $this->data['Upload'][0]['file']['type']
				)
			);
		
		
		//Check if empty file
		if ($this->data['Upload'][0]['file']['size'] == 0)  {
			//$this->redirect('http://www.error.com/');
			echo '<div style="margin:10px 0">';
			echo 'The file is empty. Please try again';
			echo '</div>';
			
    

			
			
			

		}
		
		

		
		if($this->Upload->save($data, array('validate'=>true))) { // validate now
		
		

		if(!$this->FileUpload->upload($this->data['Upload'][0]['file'])) {
		
		
		
		$this->Upload->delete($this->Upload->id); // remove the DB entry because there were upload errors
		$this->redirect('/'); //Redirect after saving
		}
		}
		
		}
		}
		
} 
?>

//view code
<?php

echo $form->create('Upload',array('name'=>'form1','type'=>'file', 'url' => 'uploads','class'=>'form')); 
echo $form->input('0.file',array('type'=>'file','label'=>'File Upload:'));
echo $form->input('comp_id', array('type'=>'hidden', 'value'=>$competitionid));
echo '<div style="padding:10px;">&nbsp;</div>';
echo '<label><input type="checkbox" id="enableSubmit" onclick="enableSubmitBtn(this.checked);">';
echo '<a href="'.$this->webroot.'tac" rel="shadowbox;width=890px" style="font-size:100%; text-decoration:none; margin-left:10px;">I agree to the terms and conditions.</a>';
echo '</label>';
													
													
echo '<span class="hide" name="mySubmit" id="mySubmit">';
echo $form->end('Submit');
echo '</span>';

?>

//and finally here is the component

//component code
<?php

class FileUploadComponent extends Object {
      var $components = array('RequestHandler');
	  

  
      protected $folder;
      protected $destination;
	  protected $fullpath;
      
      function upload($data) {            
            
            if(!is_dir($this->fullpath)) 
        { 
			
			$this->folder = date('Y-m-d_H-i-s');
            $tempdest  = 'img/uploads/';
          
            $this->fullpath = $tempdest;
			
			$this->destination = $this->fullpath.'/'.$this->folder.'-'.$data['name'];
			
            if(move_uploaded_file($data['tmp_name'], $this->destination)) {
                  
                  return true;
            }  
            return false;
      }
  }

           

  public function getDestination() {
    return $this->destination;
  }

  public function getFolder() {
    return $this->folder;
  }
  
    public function getFullpath() {
    return $this->fullpath;
  }
}



?>

Open in new window

0
error77
Asked:
error77
  • 6
  • 4
  • 2
  • +1
1 Solution
 
PrograministratorCommented:
Hello,

where's the Initialization of the $upload_info array? and what's its values?
0
 
error77Author Commented:
Codebot : Seen that link but still couldn't get mine to work :o/


Prograministrator: Is it the DB structue you are after?

If so... please see attached below

thanks



CREATE TABLE IF NOT EXISTS `entries` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `competition_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `directory_name` varchar(255) NOT NULL,
  `type` varchar(50) NOT NULL,
  `size` varchar(50) NOT NULL,
  `created` datetime NOT NULL,
  `finalist` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ;

Open in new window

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
PrograministratorCommented:
No, I meant this :

function validateFile($data, $required = false) {
$file = array_shift($data); // for easier handling

if ($required && $file['size'] == 0) {
	
	echo 'This file is invalid or empty!';
	
}
 // If no file is uploaded
if ($file['error'] !== 0) return false; // PHP Errors 
if ($upload_info[‘error’] !== 0) {	return false; }
return is_uploaded_file($file['tmp_name']); // If everything is fine

}

Open in new window


this row :
if ($upload_info[‘error’] !== 0) {	return false; }

Open in new window


$upload_info not Initialized, so this condition always return false.
0
 
error77Author Commented:
OK I've changed it to true but still when I submit an empty upload ... in other words...submit no file it doesn't stop me.

Only this code from the controller gives a message:

//Check if empty file
            if ($this->data['Upload'][0]['file']['size'] == 0)  {
                  echo '<div style="margin:10px 0">';
                  echo 'The file is empty. Please try again';
                  echo '</div>';
                  
but the above shouldn't be needed right?
   

                  
                  
                  
0
 
error77Author Commented:
Any ideas please?
0
 
PrograministratorCommented:
OK, have you tried submitting file what does it returned?

And what do you want to return if there isn't a file submitted?
0
 
error77Author Commented:
Basically there are 2 main things I need it Niot to do.

1. Not let me upload nothing
2. Not let me upload invalid extensions..

 'rule' => array('extension',array('jpg','gif','jpeg','tif','png','mov','mp4','flv','swf')),

Know what I mean?
0
 
PrograministratorCommented:
What's the name of the file field that shown in browser?

Maybe that, this validation not applied on it's name correctly.
0
 
Ray PaseurCommented:
I cannot really follow the code example posted with the question, but I can suggest a couple of ideas.  Start using the PHP function filter_var().
http://us.php.net/manual/en/function.filter-var.php

To test the file extension, you might use something like this:

$ftype = end(explode('.', $filename);
$valid - array('jpg','gif','jpeg','tif','png','mov','mp4','flv','swf');
if (!in_array(strtolower($ftype), $valid))
{
    "FILE IS OF TYPE $ftype AND NOT ALLOWED";
    /* HANDLE ERROR */
}
0
 
error77Author Commented:
Sorry that didn'ty work...code errors
0
 
Ray PaseurCommented:
As nearly as I can recall, "didn't work code errors" is not in the lexicon of error messages.  If we are to have any hope of helping you with anything other than abstract and theoretical answers, we need to see the code, the data and the error messages.  It needs to be complete.  So please post those things here, thanks.
0
 
error77Author Commented:
fixed. Thanks
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 6
  • 4
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now