Solved

Cakephp Validation not working

Posted on 2010-11-15
13
873 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
Comment Utility
0
 
LVL 3

Expert Comment

by:Prograministrator
Comment Utility
Hello,

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

Author Comment

by:error77
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Any ideas please?
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 3

Expert Comment

by:Prograministrator
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Sorry that didn'ty work...code errors
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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
Comment Utility
fixed. Thanks
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

This article discusses four methods for overlaying images in a container on a web page
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

772 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

10 Experts available now in Live!

Get 1:1 Help Now