Solved

Cakephp Validation not working

Posted on 2010-11-15
13
880 Views
Last Modified: 2012-08-14
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
Comment
Question by:error77
  • 6
  • 4
  • 2
  • +1
13 Comments
 
LVL 6

Expert Comment

by:Codebot
ID: 34140166
0
 
LVL 3

Expert Comment

by:Prograministrator
ID: 34140172
Hello,

where's the Initialization of the $upload_info array? and what's its values?
0
 

Author Comment

by:error77
ID: 34140366
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
 
LVL 3

Expert Comment

by:Prograministrator
ID: 34140477
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
 

Author Comment

by:error77
ID: 34140822
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
 

Author Comment

by:error77
ID: 34141078
Any ideas please?
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 3

Expert Comment

by:Prograministrator
ID: 34141189
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
 

Author Comment

by:error77
ID: 34141251
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
 
LVL 3

Expert Comment

by:Prograministrator
ID: 34141499
What's the name of the file field that shown in browser?

Maybe that, this validation not applied on it's name correctly.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 34142364
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
 

Author Comment

by:error77
ID: 34143629
Sorry that didn'ty work...code errors
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34145513
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
 

Author Closing Comment

by:error77
ID: 34147187
fixed. Thanks
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now