Thursday, February 26, 2009

Form ticket

This makes sure that the submitted form is from the same server.
  1.    
  2. class New_Form extends Zend_Form  
  3. {  
  4.     public function init() {  
  5.         $ticket = $this->_ticket();  
  6.         $sessionZendForm = new Zend_Session_Namespace('Zend_Form');  
  7.         $sessionZendForm->ticket = $ticket;  
  8.         $ticketElement = new Zend_Form_Element_Hidden('Form_Session_Ticket');  
  9.         $ticketElement->setValue($ticket);  
  10.         $this->addElement($ticketElement);  
  11.     }  
  12.   
  13.     public function isValid($data) {  
  14.         $ticketElement = $this->getElement('Form_Session_Ticket');  
  15.         if ($ticketElement != NULL) {  
  16.             $sessionZendForm = new Zend_Session_Namespace('Zend_Form');  
  17.             if ($sessionZendForm->ticket != $ticketElement->getValue()) {  
  18.                 throw new Zend_Form_Exception("Submitted form is not from this server.");  
  19.             }  
  20.         }  
  21.         return parent::isValid($data);  
  22.     }  
  23.   
  24.     protected function _ticket() {  
  25.         return md5(uniqid(rand(), true));  
  26.     }  
  27. }  

No comments: