David Hurth's blog

Easy Server Side Caching in PHP


When developing dynamic web applications there may be many times that data is not updated for a certain amount of time. In PHP it is fairly simple to have a page cached, so that there is not much load on the server.

To create this caching you would put some code like the following on the top of your PHP page.

$cachefile = 'caching_folder/cachedpage.html';
$cachetime = 30;
// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
ob_start(); // Start the output buffer

The things that you would change in the above code is the setting of the $cachfile variable to the name of the static file that the cache will be saving on the server (you will need to set permissions on the folder where you want to save the cached file). You will also want to change the $cachetime variable to the number of seconds between each caching.

Now you would put all of your standard PHP code to create the page after the above code. Once you have all of your standard PHP code you would put the below code to actually save the cache file.

// Cache the output to a file
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
ob_end_flush(); // Send the output to the browser

This script is very handy and a version of it is used in the del.icio.us Spy application to avoid too many calls to the del.icio.us servers.

PostgreSQL 8.3 - Finally Released!


After much waiting ProstgreSQL 8.3 has been released. This is a much better performing release from version 8.2. You can find some benchmarks that I wrote about previously here.

Below is an excerpt from the press release:

4 February 2008, New York, NY: The PostgreSQL Global Development Group today announced the release of version 8.3 of the high-performance object-relational database management system. This release includes a record number of new and improved features which will greatly enhance PostgreSQL for application designers, database administrators, and users, with more than 280 patches by dozens of PostgreSQL contributors from 18 countries.

"The continued evolution of the open source PostgreSQL database gives users the option of deploying a non-proprietary database, allowing them to save money, improve performance and increase productivity. PostgreSQL 8.3 is an impressive new release and we encourage customers around the world to explore it," said Rich Green, executive vice president of software at Sun Microsystems.

Version 8.3 provides greater consistency of performance than previous versions, ensuring that every user can depend on the same high performance demonstrated in recent benchmarks for every transaction, whether in peak hours or not, seven days a week, 52 weeks per year. Major performance enhancements include:

* Heap Only Tuples (HOT), which eliminate up to 3/4 of the maintenance overhead of frequently updated tables
* Spread checkpoints and background writer autotuning, which reduce the impact of checkpoints on response times
* Asynchronous commit option for much faster response times on some transactions

These changes also significantly accelerate transaction processing throughput, between 5% and 30%, depending on the workload.

"PostgreSQL just got smarter," said Bruce Momjian, PostgreSQL Core Team member.

PostgreSQL is the first open source database to implement Synchronized Scan, which greatly reduces I/O for data mining. The Windows team has enabled Visual C++ compilation of PostgreSQL, improving stability and performance on Windows, as well as accessibility to the project to Windows contributors. New logging options have been added and the overhead of the statistics collector has been diminished in order to make it easier to monitor your servers.

Of course, this wouldn't be a proper PostgreSQL release without providing lots of new features for application developers, including:

  • ANSI-standard SQL/XML support, including XML export
  • Text search: our advanced full text search tool, TSearch2, has been merged into the core distribution with better management and new dictionaries and languages
  • GSSAPI and SSPI authentication support
  • New data types: UUIDs, ENUMs and arrays of composite types

"We process over 18,000 queries per second on over 300GB of user data on our PostgreSQL servers, and those numbers go up every month," said Gavin Roy, CTO of social networking site MyYearbook.com. "We're very excited about HOT, shared buffer scan improvements and integrated tsearch indexing. Preliminary testing shows that 8.3 will improve our database load profile while decreasing response times. We're really looking forward to it."

In addition to the many new core features, several new optional components have matured and released 1.0 versions during the 8.3 release cycle. These include SNMP support, horizontal scalability options such as PL/Proxy, pgPool-II, and Bucardo, a graphical debugger for stored procedures, and a scalable connection pooler called pgBouncer. These add to the rich set of accessories already available.

You can read the full release here.

If you are using PostgreSQL 8.2, I definetly recommend upgrading to version 8.3.

You can download the version 8.3 here.

del.icio.us Spy - New Features


Ajaxonomy's del.icio.us Spy has received quite a positive response around the blogosphere, however, there is always room for improvement. So, having read some comments from people we have decided to make some of the improvements that where in these comments.

The improvements and new features can be found below:

Improved Filtering: The previous version filtered links based on the title of links. The new version filters links based on the links del.icio.us tags.

Submitter User Id: The new version displays the user id of the submitter of the link. This allows for users to view other links from users that they think provide interesting links.

Save For Later: The application now has a Save For Later feature which puts the links that the user thinks are interesting into a temporary holder, so he can go back later and investigate the link. If they like the link they can permanently save it using del.icio.us or another social site.

We hope that you continue to find the del.icio.us Spy useful and would love to hear any additional feedback that you have.

You can get to the application from the Ajaxonomy Labs section of this site (on the right side bar) or you can go to the application here.

Easy No Table Design Using the YUI CSS Grid Builder


In designing a web page most of us know that it is better to stay away from using tables in our design and instead use full CSS. This is great in theory, but in practice it can be quite a bit more complicated.

Well, Yahoo! has felt our pain and has built a visual tool to make page layout much easier. The tool is the Yahoo! User Interface CSS Grid Builder.

The tool is very easy to use, you simply click the various option to create the page layout that you would like. Once you have the page how you would like it, you simply click on the "Show Code" button and then copy and paste the code. Now you can start scripting and adding content to your page.

If you aren't already using this tool you should at least check it out (click here to go to the application).

Microsoft + Yahoo! = Micrahoo!?


I'm sure that you have already heard about the possibility of Microsoft buying Yahoo!. I'm not going to go in to much detail about deal, as I'm sure that you've already had your fill of that. Instead, I want to take a brief look into how this may affect Yahoo! in the future.

If Microsoft does in fact buy Yahoo!, it is very possible that all new development will be using Microsoft technologies instead of the current technologies. When I heard of this deal, the first thing I thought was that all the future development will be done in .NET technologies and run on Windows servers (can you say "nightly reboot"?).

From a web developers perspective, I really like the work that Yahoo! has done with the Yahoo! User Interface toolkit, but if Microsoft buys Yahoo!, will development stop as Microsoft tries to push Silverlight? Not to mention the possibility of abandoning JSON as Microsoft seems to prefer XML for Ajax applications.

I personally look at this with the worry that Yahoo! will stop being an innovator, as Microsoft looks to compete with Google and push their own technologies.

I would love to hear your thoughts on this, you can leave a comment or write a blog post with your free account on this site (once you login click on "Create content" => "Blog entry").

Debugging PHP


Even though I really enjoy developing in PHP there are times that debugging an issue can be very frustrating. I found a good tutorial on debugging PHP.

Below is an excerpt from the tutorial.

Starting with the Basics - Parse Errors

Parse errors can be one of the most irritating bugs for new PHP programmers to solve. A missing quote ("), bracket ({,}), and a multitude of other errors can be thrown by the interpreter which may leave you asking "What is wrong?".

Consider this code:

PHP Code:


print "Hello World;


You may notice the missing " after World and before ;. When this code is ran it casts the error:

Parse error: syntax error, unexpected $end in C:\wamp\www\broken.php on line 5

Which may leaving you asking, what is wrong with line 5?

Line 5:

PHP Code:


The line numbers may be a little deceiving at first, causing a new PHP programmer to overlook the problem. The real issue is caused because the interpreter sees a quote before Hello and assumes a string will follow. With no ending quote, the interpreter reaches the end of the script, but never completes the string assignment.

When such an error is cast, take a look at the actual line first. In this case: ?>. If no immediate errors appear start working your way backwards line-by-line. Do a quick scan of each line making sure you have terminated them correct (;). Make sure matching pairs have an ending pair (in this case the quote).

Examples of matching pairs:
[ ]
{ }
" "
' '

Now consider the following code:

PHP Code:


if $yourName == "Jordan")
"Hello $yourName";

At a closer look, you see that line 4 is missing the opening (. When this code is ran the interpreter will produce the following error:

Parse error: syntax error, unexpected T_VARIABLE, expecting '(' in C:\wamp\www\broken.php on line 4

Notice this error message correctly states the line number where the error occurred which is why it is very important to start on the line number given and work backwards. What actually happened was the interpreter read the "if" keyword and expected an open parenthesis followed by a condition. Instead it read "$yourName", a T_VARIABLE or token. What this message translates into is "While on line 4, I was expecting a '(' but received a variable."

You can view the full tutorial here.

I hope this helps you when you run into an issue coding PHP.

As always, if you find anything cool you can blog about it on this site with your free account (Once logged in click on "Create content" => "Blog entry" and then blog away).

The Future of JSON


I am a huge supporter of JSON as a means of communicating with the server side in an Ajax application (you can use JSON as a means of communication on all tiers of an application using a library, but I'm going to mainly focus on the client side for this post). I was looking into the future of JSON and found two great posts by John Resig.

The first is about the need for native JSON support.

The post goes into a lot of detail about the performance benefits of JSON and has some great code samples.

Below is the summery excerpt from the post.

The current, recommended, implementation of JSON parsing and serialization is harmful and slow. Additionally, upcoming standards imply that a native JSON (de-)serializer already exists. Therefore, browsers should be seriously looking at defining a standard for native JSON support, and upon completion implement it quickly and broadly.

To get the ball rolling, I recommend that you vote up the Mozilla ticket on the implementation, to try and get some critical eyes looking at this feature, making sure that it's completely examined and thought through; and included in a browser as soon as possible.

You can read the full post here.

The second post is about the current state of JSON and goes into detail about ECMAScript proposals for the API.

Below is an excerpt from the post about the Mozilla implementation of native JSON.

Mozilla Implements Native JSON - Mozilla was the first to implement native JSON support within it's browser. Note, however, that this is not a web-page-accessible API but an API that's usable from within the browser (and by extensions) itself. This was the first step needed to implement the API for further use.

Here is an example of it in use (works within an extension, for example):

var nativeJSON = Components.classes["@mozilla.org/dom/json;1"]
nativeJSON.encode({name: "John", location: "Boston"});
// => '{"name":"John","location":"Boston"}'
// => {name: "John", location: "Boston"} 

You can read the full post here.

Hopefully the future will have native support for JSON. As usual John does a great job on the post and if you don't have John's blog on your feed reader I recommend adding it (he is a very good Ajax development reference).

Web-based PDF Viewer

Have you ever wanted to make a PDF available by embedding it into a web page? Well now you can with Vuzit.

Below is how the makers of the application describe it.

Vuzit is a web-based universal office document viewer you can embed in any web page to help maintain consistent branding and site navigation. It provides document security and increases revenue by improving accessibility and user experience.

One of the biggest advantages is the protection of stolen data. It makes it more difficult to steal content as it can't be downloaded.

The below code is an example of how you would code a basic viewer.

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <link href="http://vuzit.com/stylesheets/Vuzit-2.1.css" rel="Stylesheet" type="text/css" />
    <script src="http://vuzit.com/javascripts/Vuzit-2.1.js" type="text/javascript"></script>

    <script type="text/javascript">
      // Called when the page is loaded.  
      function initialize()  {
        var viewer = new vuzit.Viewer(document.getElementById("vuzit_viewer"));
        viewer.setUrl("http://www.welcomingcenter.org/documents/PMP.pdf", { zoom: 1, page: 2 });

  <body onload="initialize()">
    <div id="vuzit_viewer" style="width: 650px; height: 500px;"></div>

Currently the API only supports PDF files, but more formats will be added in the near future.

You can get more information and get more code samples at vuzit.com

Ajaxonomy's del.icio.us Spy - Released!


You are probably familiar with Digg Spy, but I was very surprised when I found out that there was no similar application for del.icio.us (if you are not familiar with del.icio.us it is a great social bookmarking site).

So, we at Ajaxonomy we decided to make our own del.icio.us spy application. The application allows you to see the latest bookmarks being added to del.icio.us so that you can find great new sites. The application also includes links to help make it easy to share what you find with others.

The application allows you to filter results (i.e. type in "web" and you will only see links containing the word web) and to be notified (via sound) when new items are added. The application also allows you to pause the items that are shown so if you find something you like you can see it for a while.

You can go to the application by clicking here. The application will also be available in the Ajaxonomy Labs section on the right bar of this blog.

As with all the applications in the Ajaxonomy Labs section, this application is open source and you can download the source code here.

Cross Browser Sound in JavaScript

When working on an upcoming project I had the need to play sound through JavaScript. The method had to be cross-browser compatible, so I couldn't use any IE only calls.

Happily, I found a nice API called SoundManager2 which uses Flash to play the sound and is called through JavaScript. The API is very easy to use and below is a sample of how to use it.

The below code would be put inside the head tag of your web page.

<script type="text/javascript" src="soundmanager2-jsmin.js"></script>
<script type="text/javascript">

soundManager.url = 'soundmanager2.swf'; // override default SWF url
soundManager.debugMode = false;
soundManager.consoleOnly = false;

soundManager.onload = function() {
  // soundManager is initialised, ready to use. Create a sound for this demo page.

The part of the above code that you will be most interested in is the last line. The soundManager.createSound('aDrumSound','button-0.mp3'); is what actually loads the sound file.

The below code will cause the sound to play.


You can go to the project page by clicking here and get more information about the API. Also, you can download the files needed to use the API (including documentation and demos) here.

The library would be very useful in many applications including JavaScript games. If you create any cool applications using the API I would love to hear about it. You can post a blog entry about it when you create a free account (once you login just click on "Create content" => "Blog Entry") on this blog.

Syndicate content