Encrypt session data in PHP

Zimuel writes; As promised in my last post I present an example of strong cryptography in PHP to secure session data.
This is a very simple implementation that can be used to improve the security of PHP applications especially in shared environments where different users have access to the same resources. As you know, the PHP session data are managed by default using temporary files. In shared environment a malicious user that is able to access to these temporary files can easly read the session data because they are stored in plaintext (data in a session file is theserialization of the array $_SESSION).
In theory, the session data should be stored in folders that are accessible only by the owner of the web site, but never say never (btw, you can manage the location of the session data using the session_save_path function or changing the session.save_path in the php.ini).

To secure the session data I used strong cryptography to encrypt the content using the mcrypt extension of PHP. I chosen the simmetric cipher AES (Rijandel-256) to encrypt the session data and the openssl_random_pseudo_bytes() function to generate a random key of 256 bit.
The idea is to use a cookie variable to store the key that will be used to encrypt the session data. In this way the key is stored only in the client (the browser) and only the client is able to decrypt the session data on the server. Each time we encrypt the session data we re-generate the IV vector in a random way using the mcrypt_create_iv() function. It is very important to generate a unique IV in each encryption. This best practice increase the security of the encryption algorithm.
It’s important to note that this implementation is not secure against session hijacking attack. If someone is able to capture the cookie variable of a client and have access to the temporary session files, in the server, he/she will be able to decrypt the session data. Our goal is to protect session data against attacks on shared environments.

The idea to encrypt the session data is not new, for instance Chris Shiflett proposed an implementation in his book “Essential PHP Security” (O’Reilly, 2006). Shiflett used a $_SERVER variable to store the key used to encrypt the session data. Kevin Schroeder, my colleague at Zend Technologies, implemented a very similar session encryption algorithm extending the Zend_Session class of Zend Framework (you can find it here). In my solution, I used some of the best practices related to strong cryptography to implement a secure session handler.

Below the source code of my implementation:

Full class @ Zimuel’s blog.

XML to JSON in PHP

Zimuel writes; Last friday, in occasion of the April Zend Framework Bug-Hunt, I started to look at this bug: ZF-3257. This is an issue related to the Zend_Json class that occurs during the conversion from XML to JSON for some specific XML documents, like this one:

$xml= 'bar';

The result using Zend_Json::fromXml($xml, false) , where false indicated the usage of XML attributes, was:

{"a":{"b":{"@attributes":{"id":"foo"}}}}

As you can see the bar value, of the a element, is not represented in JSON. This issue comes also with other XML documents, and in general when an XML node has a single character data child, any attributes are lost.

For instance, the following code:

$xml = 'bar';
echo Zend_Json::fromXml($xml, false);

Produced the output:

{"a":{"b":"bar"}}

in this case the attribute id and the value foo are lost.
Find a solution @ Zimuel’s blog.

Create daemons in PHP

 

Kevin van Zonneveld wrote a life saving article that saved me quite a bit of time; Everyone knows PHP can be used to create websites. But it can also be used to create desktop applications and commandline tools. And now with a class called System_Daemon, you can even create daemons using nothing but PHP. And did I mention it was easy?

What is a Daemon?

A daemon is a Linux program that run in the background, just like a ‘Service‘ on Windows. It can perform all sorts of tasks that do not require direct user input. Apache is a daemon, so is MySQL. All you ever hear from them is found in somewhere in /var/log, yet they silently power over 40% of the Internet.

You reading this page, would not have been possible without them. So clearly: a daemon is a powerful thing, and can be bend to do a lot of different tasks.

Why PHP?

Most daemons are written in C. It’s fast & robust. But if you are in a LAMP oriented company like me, and you need to create a lot of software in PHP anyway, it makes sense:

  • Reuse & connect existing code Think of database connections, classes that create customers from your CRM, etc.
  • Deliver new applications very fast PHP has a lot of build in functions that speed up development greatly.
  • Everyone knows PHP (right?) If you work in a small company: chances are there are more PHP programmers than there are C programmers. What if your C guy abandons ship? Admittedly it’s a very pragmatic reason, but it’s the same reason why Facebook is building HipHop.

Read the full article here >>Create daemons in PHP.

A Zend Framwork compound form element for dates

Rob Allen writes; A while ago I needed to ask a user for their date of birth on a Zend_Form. The design showed three separate select elements to do this:

Screen shot of a 3 select boxes for a date on a form

A little bit of googling found this site http://codecaine.co.za/posts/compound-elements-with-zend-form which has not unfortunately disappeared, so the code in this article owes a lot of the author of that article.

It turns out to be remarkably simple to create a single Zend Form element that is rendered as multiple form elements. We create an element object and a view helper object and we’re done. Usage then looks like:

< ?php class Application_Form_Details extends Zend_Form { public function init() { $this->addPrefixPath('App_Form', 'App/Form/');

// other elements before

$this->addElement('date', 'date_of_birth', array(
'label' => 'Date of birth:'
));

// other elements after

$this->addElement('submit', 'Go');
}
}

Obviously, this form lives in application/forms/Detail.php and is rendered as usual in a view script. In our form definition, we have added an element called ‘date’ and with the addition of the addPrefixPath call have told the form that in addition to using the standard Zend Framework form elements, also look in library/App/Form. (Incidentally, we can also now override any supplied form element by simply dropping a replacement into the libraryApp/Form folder.)

The date form element lives in library/App/Form/Element/Date.php as Zend_Form knows to look in a subfolder for App/Form called Elements for any element objects and will look in the Decorator/ sub folder for decorator objects.

The Date element looks like this:

Read the rest at Rob Allen’s DevNotes.

Usage of the Conditional Ternary operator to reduce brace and newline waste when processing optional method parameters

ralphschindler writes; Usage of the Conditional Ternary operator to reduce brace and newline waste when processing optional method parameters

< ?php class Coordinate { protected $x; protected $y; public function __construct($x = null, $y = null) { (empty($x)) ?: $this->setX($x);
(empty($y)) ?: $this->setY($y);
}

/* What we're trying to replace
public function __construct($x = null, $y = null)
{
if ($x) {
$this->setX($x);
}
if ($y) {
$this->setY($y);
}
}
*/

public function setX($x)
{
$this->x = $x;
}
public function setY($y)
{
$this->y = $y;
}
}


via Gist.

Zend Studio & Eclipse Code Templates and Snippets for PHP

Saša Stamenković writes; I know many of us have struggled with coding PHP using various text editors and IDE-s. Sooner or later, we pick our favourite weapon of choice and use it for every day development. My weapon of choice is Eclipse PDT (Helios) and today I will talk about code templates.

Just to make it clear, the main reason I started to write this article is to have one place where I have my code templates stored and to prevent myself repeating this story again and again to young developers. So, don’t expect miracles. But, if you know how to work with code templates, my templates can be useful as a good starting point. When I decided to make my code templates and stick to them during the development, I first tried to google out if there is already some templates repo or good example. Unfortunately, I have found nothing.

Read full article at Umpirsky Software Development Blog.

ExtJs, ExtDesigner and Zend Framework

Nils-Fredrik G. Kaland writes; Let’s say you are working on the user interface in Ext Designer / Sencha Ext Js, and after a while you find out you have ended up with a great amount of data stores. You also need to handle lots of Ajax requests and all the server side coding this invokes. But, why not think two steps forward already when working with the interface in Ext Designer? Of course, you are an experienced developer – so you have your database model ready. More on that later. Let’s start with the user interface in Ext Designer.

via ExtJs, ExtDesigner and Zend Framework

About using UTF-8 fields in MySQL

Joshua Thijssen writes; I sometimes hear: “make everything utf-8 in your database, and all will be fine”. This so-called advice could not be further from the truth. Indeed, it will take care of internationalization and code-page problems when you use UTF-8, but it comes with a price, which may be too high for you to pay, especially if you have never realized it’s there..Indexing is everything… or at least.. good indexing makes or breaks your database. The fact remains: the smaller your indexes, the more index records can be loaded into memory and the faster the searches will be. So using small indexes pays off. Period. But what has got this to do with UTF-8?

Read the entire article here>>  A day in the life of…

Handling exceptions in a Front Controller plugin – Rob Allen’s DevNotes

Rob Allen wites in his DevNotes; If you have a Zend Framework Front Controller plugin which throws an exception, then the action is still executed and then the error action is then called, so that the displayed output shows two actions rendered, with two layouts also rendered. This is almost certainly not what you want or what you expected.

This is how to handle errors in a Front Controller plugin:

  1. Prefer preDispatch() over dispatchLoopStartup() as it is called from within the dispatch loop
  2. Catch the exception and the modify the request so that the error controller’s error action is dispatched.
  3. Create an error handler object so that the error action works as expected.

This is the code:

< ?php class Application_Plugin_Foo extends Zend_Controller_Plugin_Abstract { public function preDispatch(Zend_Controller_Request_Abstract $request) { try { // do something that throws an exception } catch (Exception $e) { // Repoint the request to the default error handler $request->setModuleName('default');
$request->setControllerName('error');
$request->setActionName('error');

// Set up the error handler
$error = new Zend_Controller_Plugin_ErrorHandler();
$error->type = Zend_Controller_Plugin_ErrorHandler::EXCEPTION_OTHER;
$error->request = clone($request);
$error->exception = $e;
$request->setParam('error_handler', $error);
}
}

}

That’s it.

via Rob Allen’s DevNotes.