knightly

Blog Archives

Voices of the ElePHPant

Just found this nice little project Cal Evans is doing. It’s called Voices of the ElePHPant. The name i guess is dedicated to Vincent Pontier the creator of the elePHPant. The goal is to shine a light on a special PHP community person. And the kick of is done by Jeremy Kendall. Be sure to check back often for new updates. Or nominate somebody.

Dark theme for Zend Studio 8

Because i was so happy with my new 3 monitor configuration. I decided to refresh my development environment as well. Normally all my files would reside in the Devspace older in my user folder under the /home directory. Now i used a new 500 GB SATA drive and formatted it EXT3. Moving your workspace in Zend Studio has the minor inconvenience that the local settings like fonts / syntax colours are lost. I still haven’t found a way to export this. So i decided to take this opportunity to create a nice new dark theme.. My friend Bart (still no blog?) was friendly enough to let me know how to export the theme related data in ZS. And was nice enough to send me his zenburn theme.

File > Export > General > Preferences

File > Import > General > Preferences

Bart’s zenburn theme:

Most developers i know don’t seem to care much about the colour of their screen and the font they use. But considering the fact that i spend an insanely amount of time behind a screen. It would be nice if this environment i am in all day put the least amount of constrained on my eyes as possible. So i choose to take time and configure this for optimal viewing pleasure. This starts with the font. For years i have been using the Envy Code font by Damien Guard inside my IDE. This all started i think with a post by Jeff Atwood It’s a great font that is extremely easy to read even for terminals. Although still in beta. I advice people to use it when possible.

The second thing i configure are the colour schemes my IDE uses. The standard colour always has a white background. White makes sure things are clear. But staring at a white screen for more then 6 hours always resulted in headaches for me. So the darker the better. And with a dark background you are forced to change the rest as well.

Changing the font is first

General > Appearance > Colors and Fonts
Font : Envy Code R Bold (11 pt)

Second up are some general text editor colours

General > Editors > Text Editors
Line number foreground : #787878 (120, 120, 120)
Current line highlight : #35353D (53, 53, 61)
Background color : #25252D (37, 37, 45)

And finally the PHP syntax coloring

PHP > Editor > Syntax Coloring
Decprecated : #000 (0, 0, 0)
Fields : #FFFFFF (255, 255, 255)
Heredoc : #008282 (0, 130, 130)
Keyword : #DE5727 (222, 87, 39)
Multi-line comment : #557F5F (85, 127, 95)
Normal : #FFF (255, 255, 255)
Number : #FFCECE (255, 206, 206)
PHP tags : #DE5727 (222, 87, 39)
PHP Doc : #FEC601 (254, 198, 1)
PHPDoc Comment : #FEC601 (254, 198, 1)
single line comment : #FEC601 (254, 198, 1)
static fields : #FFFFFF (255, 255, 255)
static methods : #FFFFFF (255, 255, 255)
String : #B3C0C8 (179, 192, 200)
Task Tags : #FEC601 (254, 198, 1)
Variable : #0B91B7 (11, 145, 183)

The result can be viewed below

There are much more configuration options to do but for now this is what i came up with. Setting up the theme is a since in ZS. But one thing bothered me. The function / property name highlighting when you select an element inside the IDE. Was a very light colour. And this made it impossible to read the contents of the selection.

So after searching for a while and setting every possible setting in the configuration tabs. I finally figured out how the set the colour for these two actions. This is done from the Annotations setting in the Text editors panel under the general tab. The two options to change are PHP elements read / write occurrences.

For now i settled with a dark colour. But maybe i will change this in the future since it is not very readable

That’s it for now. This of course only sets up the PHP environment. The syntax colours for XML, HTML, CSS and Javascript still have to be changed. But i will leave it at this.

You want to do what with PHP?

I finally took the time to read ‘You want to do what with PHP?‘. Normally i would not write about the books i read. But this book is a bit different. And since i won a copy of Kevin Schroeder’s book in a twitter sweepstake. I thought i might as well write a small review to show a bit of gratitude. I will keep it short.

Kevin is Zend Evangelist for products like the Zend Framework, Zend Server, Zend Studio and co writer of the book The IBM i Programmer’s Guide to PHP

It’s been a while since i read a PHP related book. I have been doing PHP based development for the past 10 years. And after reading almost every book of value on this topic. It’s hard to find something interesting to read about it. Most books just go over the basics. Or target a specific project / way of developing.

This book is a bit different from what i have read so far. And it will get a nice place near my other books of value. So what does make this book so different? First of all the topics that pass by are some of the more advanced topics you will come by in the PHP world. A lot of it is related to low level programming. So a bit of experience or interest in this subject is a must. Besides the advanced topics Kevin shows how to solve issues in ways i have never done them before. And that probably comes down to his experience with more low level languages like C.

He touches topics like Networking and sockets, Binary protocols, character encoding, streams, SPL, Asynchronous operations, file access, Daemons, And two great chapters about debugging, good development practises and just how to become a better developer in general. The book has a considerable amount of binary math in it which is cool. And which is also needed when doing things like handling raw TCP/IP and TCP/UDP data, writing stream handlers or creating your own file-system.

Maybe not all of the material touched in the book is relevant to web development. And most of us will probably never have to write an HTTP daemon in PHP. But the way Kevin tackles problems showed me things i never thought of before and new ways to attack old problems.

It gave me some good pointers for a webcrawler i have been working on. As i have wanted to add threading to this for a long time now. Besides that i just had a lot of fun reading this book. And would definitely advocate other developers to read it as well.

Added a review on Amazon as well.

New generation elePHPants arrived!!

Yesterday i got a message that the new generation of elePHPants are available for bulk pre-order. I am very happy the elephpant.com site is finally up and running. For the past two years i have been shipping a lot of these blue guys all across the world. No need for me to do that any more.

A big thanks for this furry blue creature goes out to:

Vincent Pontier
Damien Seguy
Christophe Villeneuve
Cesar Rodas

Compiling PHP v1.0.8

Today Rasmus posted on twitter that he just compiled PHP v 1.0.8. And it actually worked. Is that great? :) He was in need of this for his upcoming talk this week in Paris. But i couldn’t resist and try to compile this ancient piece of work ;)

$ wget http://museum.php.net/php1/php-108.tar.gz
$ tar xfvz php-108.tar.gz
$ cd php

If you need to change any config setting do it now. And hit make!

$ vi config.h
$ make

This creates a few .cgi files. So it actually does still build

phpf.cgi
phpl.cgi
phplmon.cgi
phplview.cgi

Let’s copy that to my cgi-bin and run it through Apache.

Changing Mysql for MariaDB

Ok so i quit smoking 4 days ago now. And i am having some serious sleep issues at the moment. i have been up half the night sitting here staring at my screen. But nothing really productive comes out of my hands. So while doing a bit of browsing i hit the MariaDB page. And has been while since i was here. The last time there was no real downloadable package yet. But this has all changed.

So that made me think about last week. I think it was on Friday. but there was some up stirring about MySQL (Oracle) asking a license fee for using the InnoDB storage engine. And quite a big fee if you ask me :) This really sucks. I love the InnoDB engine. What would we do without it…? That’s where MariaDB comes into play. It uses the XtraDB storage engine which is basically InnoDB on steroids. XtraDB is developed and maintained by Percona. Some really smart MySQL guys :) At the moment it’s under the GPL license. And i can only hope it will be freely available for a long time.

So i went ahead and took a look at how hard / easy it is to change MySQL for MariaDB. I tried this on a Debian Lenny machine which made the process quite easy i have to mention.

First get the PGP key from the server and import the repository locations. After that hit update to refresh the local database.

$ wget -O- http://ourdelta.org/deb/ourdelta.gpg | sudo apt-key add -
$ cd /etc/apt/sources.list.d; wget http://mirror.ourdelta.org/deb/sources/lenny-mariadb-ourdelta.list
$ aptitude update

As we can see we have some new packages

Get:8 http://mirror.ourdelta.org lenny/mariadb-ourdelta Sources [864B]
Current status: 3 updates [+3], 232 new [+11].

Searching for ‘mariadb’ gives the following packages

$ aptitude search mariadb

p libmariadbclient-dev – MariaDB database development files
p libmariadbclient16 – MariaDB database client library
v libmariadbclient16-dev – MariaDB embedded database development files
p mariadb-client – MariaDB database client (metapackage depending on the latest version)
p mariadb-client-5.1 – MariaDB database client binaries
p mariadb-client-core-5.1 – MariaDB database core client binaries
v mariadb-common
p mariadb-server – MariaDB database server (metapackage depending on the latest version)
p mariadb-server-5.1 – MariaDB database server binaries
p mariadb-test – MariaDB database regression test suite (metapackage depending on the latest version)
p mariadb-test-5.1 – MariaDB database regression test suite

So let’s go ahead and install the server and see what happens.

$ aptitude install mariadb-server

Some mysql files get removed the mysql-common package gets updated and the new MariaDB packages get installed.

The following NEW packages will be installed:
libmariadbclient16{a}
libmysqlclient16{a}
mariadb-client-5.1{a}
mariadb-client-core-5.1{a}
mariadb-server
mariadb-server-5.1{a}

The following packages will be REMOVED:
mysql-client-5.0{a}
mysql-server{a}
mysql-server-5.0{a}

The following packages will be upgraded:
mysql-common

Now that’s done. Let’s check MySQL’s output

$ mysql –version
mysql Ver 14.16 Distrib 5.1.49-MariaDB, for debian-linux-gnu (i486) using readline 5.1

Just as i expected. Nothing really changed here. The whole MySQL API is till available for calling. Only the base system is now replaced by MariaDB. So let’s see what storage engines are available.

$ mysql -uroot -p

MariaDB [(none)]> show engines;
BLACKHOLE /dev/null storage engine (anything you write to it disappears)
MRG_MYISAM Collection of identical MyISAM tables
FEDERATED FederatedX pluggable storage engine
MARIA Crash-safe tables with MyISAM heritage
CSV CSV storage engine
MEMORY Hash based, stored in memory, useful for temporary tables
ARCHIVE Archive storage engine
MyISAM Default engine as of MySQL 3.23 with great performance
InnoDB Supports transactions, row-level locking, and foreign keys
PBXT High performance, multi-versioning transactional engine

And because the MySQL APi is still in tact. From PHP we can keep using the mysql and mysqli interfaces. This is great stuff!

Jquery & PHP doing simple image slicing

Today i was in need of a basic image slicer. An there must be a million of these things out there. But i wanted to see how hard / easy it would be to create this myself.

Conclusion. It’s not that hard when using the jquery library. which is becoming my Javascript framework of choice.



I started with a div.

Then i added the placeholder for the to be scaled image. And a div that will represent the slicer borders.

The next thing to do is setup the scaling canvas. So let’s make it draggable and resizeable.

// Create a draggable / scalable slicer
       $(function() {
            $('#image_slicer')
            .draggable({containment:'#image_slicer_canvas'}) // constraint
            .resizable();

            // set the slicer canvas size
            resizeCanvas(
            	$('#image_slicer_image').width(),
            	$('#image_slicer_image').height()
            );
       });

The only thing we need now is a bit of javascript to handle the slice action. I used a sample form to do the posting to the slicer.php script

// handle slicer actions
       $('#image_slicer').resizable({
   	      stop: function(event, ui) {
   	          var pos = $('#image_slicer').position();
   	          // width, height, left, top
   	          $('#scaler_width').val($('#image_slicer').width());
      	      $('#scaler_height').val($('#image_slicer').height());
        	  $('#scaler_left').val(pos.left);
        	  $('#scaler_top').val(pos.top);
   	      }
       });

The result is a nice red dotted line (square) on top of the image. The dotted area is draggable and resizeable.
When the right slice is selected just hit the slice button and PHP/GD will do the rest.

$width  = $_POST['width'];
$height = $_POST['height'];
$left   = $_POST['left'];
$top    = $_POST['top'];

// read source image
$src = imagecreatefromjpeg('images/sample.jpg');
$dest = imagecreatetruecolor($width, $height);

imagecopy($dest, $src, 0, 0, $left, $top, $width, $height);

header('Content-Type: image/jpeg');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);

That’s all. All files can be downloaded here

Zend Studio goes virtual

Zend Studio added a new great feature to there already impressive stack of features. The IDE just keeps growing in the right direction.

So the new 8 version which at the time of writing is in Beta added VMWare support. This is a feature i was looking forward to. And couldn’t wait to give this a try. So when i got a email that the new beta is out. I didn’t wait and downloaded the behemoth.

Adding VMWare support to the IDE seems like a logical thing to do. Specially since everything is virtualized now a days. I thought about this a while. But you can use it in different setups. For me it is an extra on my development environment. I’m a big Linux enthusiast. But at the office i work on windows. So now i can develop in my own virtual Linux environment. But it’s also a great solution for running Unit Test on a production VM. Or just to test on a production VM.

My first try was on my OS of choice which is Ubuntu. That however didn’t go to well. As soon as i started the “Run as VMWare application” my IDE would die on me. I quickly gave up on this mainly because i am running Maverick which is not considered stable. And VMWare already had some problems building the kernel modules. If anybody is interested in the crash logs. I still have some.

So back to windows. Windows 7 in particular. I always keep a Windows partition laying around. For games and stuff. So i downloaded the following files.

* Ubuntu-Server
* Zend Studio 8 Beta (trial)
* VMWare 7.1.2 (trial)

Installing VMWare and Zend Studio is a since. Nothing to make note off here. After that was done i installed Ubuntu 10.04 Server edition. And installed Zend Server inside of it. That should be all.. right? So let’s launch the IDE and give it a shot. Well it launched but i got back an error like below.

At first i had no clue what was going on. But i had the feeling there was something wrong with the VMWare client tools. After digging through the Zend Studio manual i found the answer The ‘hgfs’ was not mounted on teh client OS. And this was because the vmware tools did not have enough libraries to build everything. To build the complete VMWare tools on the client OS we need

* gcc
* make
* build-essential
* linux-headers-(current version)

When that’s done it necessary to attach the linux version of the VMWare tools to the virtual CDRom drive. So we can mount it inside the VM.

/usr/lib/vmware/isoimages/linux.iso

mount /dev/cdrom /mnt

Copy the file somewhere and unmount the /mnt or the build will fail. Unpack the VMWare tools and run the perl script inside to install. Once that’s done follow the VMWare instructions. Or reboot the VM.

Now we are all set. Now it’s just a matter of writing code. And running it on the VM. When running an application as a VMWare application the IDE syncs the files with the shared folder on the VM. After that the internal browser is launched to see the result.

The first time you will be asked for the VM to use. Just point it to the VM image created by VMWare.

When no VM is active when launching the application. Zend Studio will trigger VMWare to launch the VM.

Some output in Zend Studio

Drag & drop Uploads with XMLHttpRequest2 and PHP Revised

A while back i wrote a post where i explained how to implement the new XMLHttpRequest2 object. The main point of the post was to use sendAsBinary() so we can stream file uploads from the client to the server.

The post i made showed some code snippets to make this possible. And the Javascript part is all fine and dandy. But last week i had an interesting mail conversation with Jean-Pierre Vincent about the memory consumption on the server side of things.

The result of some testing revealed the server would need at least the amount of memory equal to the file size. For small files this is no problem. But with bigger files this becomes a problem. Although i couldn’t reproduce Jean-Pierre’s results. I wasn’t very happy with the test results.

Upload 2.8 MB file results in 3.1 MB memory usage
Upload 29 MB file results in 30 MB memory usage

A bit more testing revealed that file_put_contents() was the culprit. Which seems logical if you think about it. It reads the file into memory and dumps it again. Not very elegant for big files. Besides we are trying to stream files. So why should we read them completely in to memory? We shouldn’t :)

Jean-Pierre decided to go with the DataForm object to solve the issue. I still want to look into that. But have not found any information about. Besides that i knew the problem was on the server side. So i rewrote the receive() method to be less memory intensive. The results are considerably better then before.

Upload 2.8 MB file results in 0.4 MB memory usage
Upload 29 MB file results in 0.4 MB memory usage

The memory usage was measured with memory_get_peak_usage(). And the new code is posted below:

public function receive()
{
    if (!$this->isValid()) {
        throw new Exception('No file uploaded!');
    }

    $fileReader = fopen('php://input', "r");
    $fileWriter = fopen($this->_destination . $this->_fileName, "w+");

    while(true) {
        $buffer = fgets($fileReader, 4096);
        if (strlen($buffer) == 0) {
            fclose($fileReader);
            fclose($fileWriter);
            return true;
        }

        fwrite($fileWriter, $buffer);
    }

    return false;
}

Recursive array filtering

note to self .. a nice clean way to do recursive array filters in PHP

$arr = array(
    'teSt',
    'The quick BroWn ...',
    'foO',
    array(
       'Test sTring'
    )
);

$filter = function(&$input) use (&$filter) {
    if (is_array($input)) $input = array_map($filter, $input);
    else if (is_string($input)) $input = strtolower($input);

    return $input;
};

$filter($arr);
var_dump($arr);