Saturday, September 19, 2009

Zend_Date

Using the Zend_Date class:

The following shows how you make a Zend_Date object from a MYSQL timestamp and how to do things with it.
 
$date = new Zend_Date($timestamp);

//Compare with now but first add a week.
$date->add('7', Zend_Date::DAY);
if($date->compare(new Zend_Date()) == -1) {
//$date has not accoured yet, since now is "smaller" than $date.
} else {
//$date has accoured, since now is "larger" than $date.
}

//Write it out in a way MYSQL timestamp understands
$sql_date_pattern = 'yyyy-MM-dd HH:mm:ss';
echo $date->get($sql_date_pattern);

Saturday, February 28, 2009

Encoding - UTF8

How to make sure the whole site is in UTF-8.

Send the following header.

header('Content-Type: text/html; charset=utf-8');

Can be done with Zend Framework the following way in bootstrap:

$response = new Zend_Controller_Response_Http;
$response->setHeader('Content–Type', 'text/html; charset=UTF-8', true);
self::$frontController->setResponse($response);


<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Setting the option form option:

<form accept-charset="utf-8">


In Zend_Form:

$this->setAttrib('accept-charset', 'UTF-8');

Making sure the database is also using UTF-8.
When setting up use:

$db->query("SET NAMES 'utf8'");

Zend_View can also be set to use UTF-8:

$view = new Zend_View;
$view->setEncoding('UTF-8');

Reference: http://www.phpwact.org/php/i18n/charsets

Thursday, February 26, 2009

Form ticket

This makes sure that the submitted form is from the same server.
 
class New_Form extends Zend_Form
{
public function init() {
$ticket = $this->_ticket();
$sessionZendForm = new Zend_Session_Namespace('Zend_Form');
$sessionZendForm->ticket = $ticket;
$ticketElement = new Zend_Form_Element_Hidden('Form_Session_Ticket');
$ticketElement->setValue($ticket);
$this->addElement($ticketElement);
}

public function isValid($data) {
$ticketElement = $this->getElement('Form_Session_Ticket');
if ($ticketElement != NULL) {
$sessionZendForm = new Zend_Session_Namespace('Zend_Form');
if ($sessionZendForm->ticket != $ticketElement->getValue()) {
throw new Zend_Form_Exception("Submitted form is not from this server.");
}
}
return parent::isValid($data);
}

protected function _ticket() {
return md5(uniqid(rand(), true));
}
}