Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Cakephp Validation not working

Posted on 2010-11-15
13
894 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
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 
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
 
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 109

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 109

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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

839 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