PHP generated image caching

So a recent challenge I had was storing binary data (a PNG image) in a MySQL database behind PHP, to which I would pull out upon request, format it and use it as a displayed image in the webpage.

My initial code looked very simple and easy.

header(“Cache-Control: private, max-age=10800, pre-check=10800”);
header(“Pragma: private”);
header(“Expires: ” . date(DATE_RFC822,strtotime(” 2 day”)));

header(‘Content-type: image/png’);
header(‘Content-MD5: ‘. base64_encode(pack(‘H*’, md5($row[‘Icon’]))));
header(‘Content-Length: ‘.filesize($row[‘Icon’]));
header(‘Content-Disposition: attachment; filename=”‘.$_GET[“ElementID”].’.png”‘);
echo $row[‘Icon’];

Now I wouldn’t suggest using this, as I found out Content-Length was way wrong, along with expires just set for 2 days. I needed to manually flush my browser cache to see any updates. Bad way to push out an image from MySQL through PHP.

The link below from rd2inc.com was the majority of my solution, but to that I had to change the way it got the additional header information. This was because apache_request_headers() wasn’t a function in my PHP. So in the link to php manual (below) I found and then had to slightly modify the code for the .htaccess file to this:

RewriteEngine on
RewriteRule (.*) – [E=HTTP_IF_MODIFIED_SINCE:%{HTTP:If-Modified-Since}]
RewriteRule (.*) – [E=HTTP_IF_NONE_MATCH:%{HTTP:If-None-Match}]

Now I can use:

$_SERVER[‘HTTP_IF_MODIFIED_SINCE’]
$_SERVER[‘HTTP_IF_NONE_MATCH’]

And how did I check for update change? Just set a hook in MySQL to update a timestamp  whenever that row is updated!

Links where I got info:

PHP Dev Tools

If you are a PHP developer (or an aspiring one) then you will need a development environment. If you have been trying to write a site using windows notepad, then I feel oh so sorry for you. There is help…

You will find that the industry standard are all eclipse based. eclipse is an open source IDE that is customizable for just about any programming you would need it for on just about any OS that you would like to do it on. I believe eclipse was started with the Java language, but is now used for everything from android to zend.

Aptana studio is a fork from the eclipse project with their main focus to be on building a specific application that is tailored directly for web development ventures. I have used Aptana and it is a very promising platform. Everything is present very well and the interface is definitely more clean than eclipses. With that said, I did not stick with the product for a reason in which I don’t fully remember, it has been awhile since I used the product, and if anyone has the intentions to strictly do web development and nothing more I would insist that you take a peek at aptana first. The getup-and-go ability of this application is very nice since eclipse (being as versatile as it is) does require some configuration to get it just right for your purposes.
http://aptana.com

Now for eclipse. I have used it quite a bit, everything from raw java development, to php, to android dev. I would suggest that if you have the intentions to do more than just web programming, that perhaps you start looking at eclipse. It may get frustrating trying to get the right plugins installed and configured correctly, but once everything is setup properly it is a very stable and very usable IDE. With that said you might wonder “well what version do I use?”, as you will quickly see, the eclipse download page offeres many downloads for many different types of development. I would suggest that you should download the top version, which is usually the one tailored for Java developers… but that doesnt matter because you will have to install your own custom plugins anyways which will change everything you need. Now when it comes to PHP plugins for eclipse, I believe there are a few to choose from, but hands-down you should install the PDT plugin. This stands for “PHP Development Tools”… not only is it an official plugin from eclipse, but Zend ( a very big company focused on the advancement of php) commits a lot of code and resources to the development of this plugin ( and you will soon see why). But this means that it will have the most features you need with the easiest of use and functionality. Proper code highlighting and syntax checking.
http://www.eclipse.org

Note: If you are using a Linux OS with eclipse I would strongly suggest downloading the IDE from the eclipse website rather than installing it from the source repository. I had used this method once-upon-a-time because I figured “Oh now this will keep it all updated”, but what I soon realized while trying to utilize some new(er) features is that the repo version was several years old! This was not going to work for me, so I uninstalled it and simply replaced it with a fresh download from the eclipse site. In retrospect, this is a better approach because the last thing a developer wants to deal with while in mid-project is having an auto-updater demolish his IDE (which sometimes updates do). This way helps protect yourself by knowing exactly when and why you choose to update your IDE.

Last (but not least) is Zend studio. As I had mentioned earlier, Zend is a big company focused around PHP and what it can do for companies. One of their products is of course Zend Studio. Which offers many useful tools and features specifically tailored for PHP. If you are lucky enough to have a copy of this software, it would also be likely that you are running a Zend server. In this case you will have access to a WHOLE SLEW of additional features where you can actively debug on the server, view very detailed statistics about performance and load balancing your code. It is very nice… I personally have never used the tool, but have watched a few tutorials about it, and have drooled a bit over it as well… But in the end basically it is the eclipse framework with an overhaul of the PDT plugin and a little (or a lot) of Zend spice in there to really make it a sound product. If I come around to downloading a trial version of it, I will definitely post my feedback.
http://www.zend.com/en/products/studio/

PHP Static Class Variable

Recently found out that when you serialize a class (in my case it was storing it in a $_SESSION[] variable)  that the class’s static variable gets reset to it’s default value. Consider the following:

  1. (page) script runs
  2. class constructed
  3. class used (static variable set)
  4. class serialized at end of script (automatically when stored in a $_SESSION[] variable)
  5. (new/next page) different or same script runs
  6. class deserialized (automatically by referencing you $_SESSION[] variable)
  7. !static variable is default!

This doesn’t mean what you set it to in the constructor, since the constructor doesn’t get called when an object is deserialized. Rather when you declare the variable in the class. For example:

Class User{
	private  static $loggedIn = 0;
}

So if you do not declare a default value, then your variable will simply be ‘unset’ when you reference your freshly deserialized class object.

A solution? Here is where the __magic begins!

So if the static variable isn’t preserved then you must use the magic php class functions __destruct() and __wakeup(). Consider the following, where you want to preserver whether a single user is logged in or not:

Class User{
	private  static $loggedIn = 0;
	private $thisLoggedIn;

	function isUserLoggedIn(){
		return self::$loggedIn;
	}

	function __destruct() {
		$this->thisLoggedIn = self::$loggedIn;
	}

	public function __wakeup(){
		self::$loggedIn = $this->thisLoggedIn;
	}
}

Here is what happens:

I always store and use the instance of the User class from a $_SESSION[‘user’] variable, this is important because any changes I make to the object is preserved after the script terminates and the object is serialized.

So you will see that in the destructor we have:

$this->thisLoggedIn = self::$loggedIn;

This way, at the end of the page script the destructor is called. We set the private variable $thisLoggedIn as what our static variable $loggedIn is. The importance of this is that the value of ‘self::$loggedIn’ is preserved as ‘$this->thisLoggedIn’ when the object gets serialized.

Then when the object is automatically deserialiezed, the magic php function ‘__wakeup()’ is automatically called. In this we reset the static variable to what was serialized and stored inbetween page transitions in the  $_SESSION[‘user’] variable.

The only thing that you must be sure of now is that besides in the ‘__destruct()’ and ‘__wakeup()’ calls, never use ‘$thisLoggedIn’ anywhere in the class. Always reference the static variable ‘self::$loggedIn’. That way you can be sure that what you are storing and then restoring is what your expecting.

flush()

Learned about a new technique today dealing with making the performance of your webpages faster:

<?php flush(); ?>

The article here is where I found it:
http://developer.yahoo.com/performance/rules.html

They explain that the flush() function will tell the web server to send what HTML it has ready right now to the web browser, then when it gets the rest of the content assembled it can send the rest. A ‘best-practice’ is to flush after the header of your HTML. This makes sense, because then the browser can work on downloading any external includes that you happen to have in the header (css, javascript, etc) while the server is still working on rendering the rest of the webpage.

empty()

Yes, a new ‘cool tool’ that I discovered! Since many php funcitons will return a variety of different types, and since php is a loose-type language, I have found myself using this function a LOT.

So what does it do? Here is what php.net has to say about it:

Returns FALSE if var has a non-empty and non-zero value.
The following things are considered to be empty:
  • “” (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • “0” (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)

So basically anything that would be considered a ‘false’ or a “no” is simply returned as a false. This makes my if() statements so much more shorter and readable.

A revolutionary PHP database accessing method

I knew there were object oriented approaches to making database calls, but I never sunk into learning any of them yet, as kickin’ it old-school and just issuing DB queries directly was just fast and I didn’t have to relearn anything. Well now I have discovered an improved method that after just reading the introduction and a few examples I whole-heartily support this method and I will start using it for my next DB tied project.

What is this new method you might ask? It is called “PDO” which stands for “PHP Data Objects”, this nice abstraction layer supports transaction calls, persistent DB connections, various types of automatic caching, etc…

If you were like me and just use straight up DB calls, I would strongly consider changing your ways! It is extremely easy and arguably even easier, more secure, and safer than that mundane method of the past.