Tag Archives: php

Using cookies in Lithium PHP

RDO Calender required me to use cookies to keep track of simple session information. For a while I couldn’t figure it out but after reading the unit tests I got it.


Instead of using the $_COOKIE superglobal you can use Lithium’s Session adapter to create a cookie adapter then use inside your controllers. First start off by setting up the adapter in the configuration file.
app/config/bootstrap/session.php (make sure the session.php file is uncommented in app/config/bootstrap/bootstrap.php)

	'cookie' => array('adapter' => 'Cookie', 'expire' => '+365 day'),
	'default' => array('adapter' => 'Php')

Below are all the options, taken from libraries/lithium/storage/session/adapter/Cookie.php

	 * Default settings for this session adapter.
	 * @var array Keys are in direct correspondence with the parameters in the PHP-native
	 *      `setcookie()` method. The only difference is that the `expire` value is a
	 *		strtotime-compatible string instead of an epochal timestamp.
	protected $_defaults = array(
		'expire' => '+2 days', 'path' => '/', 'name' => null,
		'domain' => '', 'secure' => false, 'httponly' => false


After the setup is done, you can read and write cookies using the Session::read and Session:write functions respectively.

Session::read($key = null, array $options = array());
Session::write($key, $value = null, array $options = array());

It’s fairly straightforward. In options you’ll have to specify the cookie that you created. Full Session::read example below.

Session::read('cal.dow', array('name' => 'cookie'));

where ‘cookie’ is the name of the adapter we created in the config.

Lithium PHP uses the ‘.’ character to give namespaces to the cookie keys. Each key is broken into sections and restructured using ‘[‘ and ‘]’. The call above will read the cookie of key “appcookie[cal][dow]”

JQuery cookie plugin

Because I was using the jquery.cookie.js plugin in conjunction; I want to point out that the plugin (and possibly others) use encodeURIComponent() to escape keys/values when setting cookies. This escaped the ‘[]’ characters used by lithium. I modified the aforementioned plugin to accept a rawKey parameter that will prevent the key from being escaped.
relevant excerpt:

return (document.cookie = [
            options.rawKey? key : encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''


These past few days I’ve been working on version 2 of Vlad Tracker. Although it may be a bit premature but I’m proud to announce the launch of nypdcalendar.com. It’s basically Vlad Tracker but adjustable so can be used by other members of the force. The default is set at his schedule but can be easily changed via the link on the bottom.

My next order of things will be branding & styling. After that I think I’ll write mobile browser friendly CSS and perhaps make the whole thing a facebook app.

PHP Calendar Month Function

I decided to start working on a follow-up project to my previous Vlad Tracker. The first version of it is pretty simple. It just lists all of his days off vertically. Next step of course is to display everything in a calendar view. The first version also focused on simplicity, including all of the scripts & styles inline so that it could be just saved on the hard drive without any messy additional files. This time it is in PHP because of the convenient date manipulation functions.

I needed a function that would generate a calendar month. After a bit of searching on google, I didn’t find any code that did what I wanted. Everything already generated html with calendar-type widgets. So I wrote my own.

PHP function getCalendarArray takes 2 arguments; a date and a number representing day of the week. The date can be either a string representing a date (as accepted by DateTime object) or a DateTime object itself. The second parameter is an integer 0-6 representing the first day of the week. 0 for Sunday, 1 for Monday … 6 for Saturday. The function returns an array where each element is an array representing a date. It’s meant to fit in a square so the first and last few days will be of the previous and next month respectively. The outer array is numerically indexed, the outer array contains the following string indexes: day, month, year, specified. Specified is a boolean representing the specific date that is passed in the first argument.

Function prototype:

function getCalendarArray([$date [, $dao_adj]])

Sample abridged return value:

  0 => 
      'day' => int 28
      'month' => int 8
      'year' => int 2011
      'specified' => boolean false
  1 => 
      'day' => int 29
      'month' => int 8
      'year' => int 2011
      'specified' => boolean false
  2 => 
      'day' => int 30
      'month' => int 8
      'year' => int 2011
      'specified' => boolean false
  3 => 
      'day' => int 31
      'month' => int 8
      'year' => int 2011
      'specified' => boolean false
  4 => 
      'day' => int 1
      'month' => int 9
      'year' => int 2011
      'specified' => boolean false
  5 => 
      'day' => int 2
      'month' => int 9
      'year' => int 2011
      'specified' => boolean false
  6 => 
      'day' => int 3
      'month' => int 9
      'year' => int 2011
      'specified' => boolean false

Basically this functions provides data on how to render the calendar but doesn’t have any of the rendering code. Making it perfect for integration into custom calendar projects. Feel free to use it however you want!

View the full source, with comments and license.

Rendering image with div tags using Javascript

As I was trying to figure out how to protect image files from being copied; I thought: Why not render them as a bitmap using <div> tags? After a bit of searching I couldn’t find any project that does this, although there are plenty of examples that use html to draw images on the page. A good one that I like is Google Pacman. The closest “implementation” I found was to use the html5 canvas tag. But that wouldn’t work for my purposes because you can right click on it and save it as an image.

Working buttom-up, I wrote the code that reads a JPEG image pixel by pixel and feeds it to the browser. Executing the below code will print the number of horizontal pixels in the image (space separator), followed by the number of vertical pixels (space separator) then followed by 6 character hex codes (no delimiters) representing the color of each pixel from left to right.

$im = imagecreatefromjpeg('test.jpg');

$sx = imagesx($im);
$sy = imagesy($im);

$colors = array();
$num_colors = 0;
echo $sx . ' ' . $sy . ' ';
for ($y = 0; $y < $sy; $y++){
    for ($x = 0; $x < $sx; $x++){
        $color = imagecolorat($im, $x, $y);
        $r = ( $color >> 16 ) & 0xFF;
        $g = ( $color >> 8 ) & 0xFF;
        $b = $color & 0xFF;
        printf("%'02X%'02X%'02X", $r, $g, $b);

This is grossly inefficient. A 10.4 KB JPEG turns into 241.41 KB. There are a number ways to makes this more efficient, like echoing out $r, $g, and $b values to the screen as characters (they’re 8 bits after all) then building the hex value in Javascript. In that case you get other issues like characters that you aren’t really supposed to use (e.g. null string).

I used GD to generate the colors from the image. I would have preferred ImageMagick; it looks like the PixelIterator would be more efficient. But my webhost doesn’t have the php extension (shamefully I don’t have it installed on my computer either). Either way you only need to generate the colors file once then can statically feed it to the renderer.

The rendering code is fairly basic. Assuming the above color data is loaded into the variable data then the result will be an imgdiv variable containing a DOM div element with the entire image rendered in divs.

var i = 0;
var sx = '';
var sy = '';
var ca = data.charAt(i);
while( ca != ' '){
	sx += ca;
	ca = data.charAt(++i);
sx = parseInt(sx);
ca = data.charAt(++i);
while( ca != ' '){
	sy += ca;
	ca = data.charAt(++i);
sy = parseInt(sy);
var color = '';
var imgdiv = document.createElement('div');
for(var y = 0; y < sy; y++){
	for(var x = 0; x < sx; x++){

		for (var j = 0; j < 6; j++){
			color += data.charAt(++i);

		var newdiv = document.createElement('div');
		newdiv.setAttribute('style', 'background-color:#'+color);
		newdiv.setAttribute('class', 'r');
		if (x == 0) {
			newdiv.setAttribute('class', 'r fp');
		else {
			newdiv.setAttribute('class', 'r');
		color = '';

Styles that I used to force the images to be 1 pixel:

div.r {
	width: 1px;
	height: 1px;
div.fp {

So… did it work? Short answer is yes, but it takes so much processing power for the browser to render it that it makes the process not worth it. You can see for yourself: render.html It takes me a notch less than 10 seconds to load & render that page, it may crash your browser if you’re running on a slow machine. This probably can be optimized, but the image is only 206×200. I hate to think what happens at 400×400 when there are 4 times as many pixels to render.

The real bottleneck is the browser, it’s not made to display thousands of 1 pixel <div> tags. With a sigh, I thought of a next idea: Why not split the jpeg into many other jpegs (say, 1 image into 100) then load them next to each other? This naturally follows: Why not scramble the image, like this puzzle, then use background position style to reassemble back on the page? Although not as cool as rendering everything in JS, this may provide some level of deterrence against image copying. I’ll make another post if I implement this idea.