Image Resizing Made Easy with PHP

Image Resizing Made Easy with PHP

Ever wanted an all purpose, easy to use method of resizing your images in PHP? Well that’s what PHP classes are for – reusable pieces of functionality that we call to do the dirty work behind the scenes. We’re going to learn how to create our own class that will be well constructed, as well as expandable. Resizing should be easy. How easy? How about three steps!


Introduction

To give you a quick glimpse at what we’re trying to achieve with our class, the class should be:

  • Easy to use
  • Format independent. I.E., open, resize, and save a number of different images formats.
  • Intelligent sizing – No image distortion!

Note: This isn’t a tutorial on how to create classes and objects, and although this skill would help, it isn’t necessary in order to follow this tutorial.

There’s a lot to cover – Let’s begin.


Step 1 Preparation

We’ll start off easy. In your working directory create two files: one called index.php, the other resize-class.php


Step 2 Calling the Object

To give you an idea of what we’re trying to achieve, we’ll begin by coding the calls we’ll use to resize the images. Open your index.php file and add the following code.

As you can see, there is a nice logic to what we’re doing. We open the image file, we set the dimensions we want to resize the image to, and the type of resize.
Then we save the image, choosing the image format we want and the image quality. Save and close your index.php file.

		// *** Include the class
		include("resize-class.php");

		// *** 1) Initialize / load image
		$resizeObj = new resize('sample.jpg');

		// *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
		$resizeObj -> resizeImage(150, 100, 'crop');

		// *** 3) Save image
		$resizeObj -> saveImage('sample-resized.gif', 100);

From the code above you can see we’re opening a jpg file but saving a gif. Remember, it’s all about flexibility.


Step 3 Class Skeleton

It’s Object-Oriented Programming (OOP) that makes this sense of ease possible. Think of a class like a pattern; you can encapsulate the data – another jargon term that really just means hiding the data. We can then reuse this class over and over without the need to rewrite any of the resizing code – you only need to call the appropriate methods just as we did in step two. Once our pattern has been created, we create instances of this pattern, called objects.

“The construct function, known as a constructor, is a special class method that gets called by the class when you create a new object.”

Let’s begin creating our resize class. Open your resize-class.php file. Below is a really basic class skeleton structure which I’ve named ‘resize’. Note the class variable comment line; this is were we’ll start adding our important class variables later.

The construct function, known as a constructor, is a special class method (the term “method” is the same as function, however, when talking about classes and objects the term method is often used) that gets called by the class when you create a new object. This makes it suitable for us to do some initializing – which we’ll do in the next step.

		Class resize
		{
			// *** Class variables

			public function __construct()
			{

			}
		}

Note that’s a double underscore for the construct method.


Step 4 The Constructor

We’re going to modify the constructor method above. Firstly, we’ll pass in the filename (and path) of our image to be resized. We’ll call this variable $fileName.

We need to open the file passed in with PHP (more specifically the PHP GD Library) so PHP can read the image. We’re doing this with the custom method ‘openImage’. I’ll get to how this method
works in a moment, but for now, we need to save the result as a class variable. A class variable is just a variable – but it’s specific to that class. Remember the class variable comment I mentioned previously? Add ‘image’ as a private variable by typing ‘private $image;’. By setting the variable as ‘Private’ you’re setting the scope of that variable so it can only be accessed by the class. From now on we can make a call to our opened image, known as a resource, which we will be doing later when we resize.

While we’re at it, let’s store the height and width of the image. I have a feeling these will be useful later.

You should now have the following.

		Class resize
		{
			// *** Class variables
			private $image;
			private $width;
			private $height;

			function __construct($fileName)
			{
			    // *** Open up the file
			    $this->image = $this->openImage($fileName);

			    // *** Get width and height
			    $this->width  = imagesx($this->image);
			    $this->height = imagesy($this->image);
			}
		}

Methods imagesx and imagesy are built in functions that are part of the GD library. They retrieve the width and height of your image, respectively.


Step 5 Opening the Image

In the previous step, we call the custom method openImage. In this step we’re going to create that method. We want the script to do our thinking for us, so depending on what file type is passed in, the script should determine what GD Library function it calls to open the image. This is easily achieved by comparing the files extension with a switch statement.

We pass in our file we want to resize and return that files resource.

		private function openImage($file)
		{
		    // *** Get extension
		    $extension = strtolower(strrchr($file, '.'));

		    switch($extension)
		    {
		        case '.jpg':
		        case '.jpeg':
		            $img = @imagecreatefromjpeg($file);
		            break;
		        case '.gif':
		            $img = @imagecreatefromgif($file);
		            break;
		        case '.png':
		            $img = @imagecreatefrompng($file);
		            break;
		        default:
		            $img = false;
		            break;
		    }
		    return $img;
		}

Step 6 How to Resize

This is where the love happens. This step is really just an explanation of what we’re going to do – so no homework here. In the next step, we’re going to create a public method that we’ll call to perform our resize; so it makes sense to pass in the width and height, as well as information about how we want to resize the image. Let’s talk about this for a moment. There will be scenarios where you would like to resize an image to an exact size. Great, let’s include this. But there will also be times when you have to resize hundreds of images and each image has a different aspect ratio – think portrait images. Resizing these to an exact size will cause severe distortion.If we take a look at our options to prevent distortion we can:

  1. Resize the image as close as we can to our new image dimensions, while still keeping the aspect ratio.
  2. Resize the image as close as we can to our new image dimensions and crop the remainder.

Both options are viable, depending on your needs.

Yep. we’re going to attempt to handle all of the above. To recap, we’re going to provide options to:

  1. Resize by exact width/height. (exact)
  2. Resize by width – exact width will be set, height will be adjusted according to aspect ratio. (landscape)
  3. Resize by height – like Resize by Width, but the height will be set and width adjusted dynamically. (portrait)
  4. Auto determine options 2 and 3. If you’re looping through a folder with different size photos, let the script determine how to handle this. (auto)
  5. Resize, then crop. This is my favourite. Exact size, no distortion. (crop)

Step 7 Resizing. Let’s do it!

There are two parts to the resize method. The first is getting the optimal width and height for our new image by creating some custom methods – and of course passing in our resize ‘option’ as described above. The width and height are returned as an array and set to their respective variables. Feel free to ‘pass as reference’- but I’m not a huge fan of that.

The second part is what performs the actual resize. In order to keep this tutorial size down, I’ll let you read up on the following GD functions:

We also save the output of the imagecreatetruecolor method (a new true color image) as a class variable. Add ‘private $imageResized;’ with your other class variables.

Resizing is performed by a PHP module known as the GD Library. Many of the methods we’re using are provided by this library.

		// *** Add to class variables
		private $imageResized;
		public function resizeImage($newWidth, $newHeight, $option="auto")
		{

			// *** Get optimal width and height - based on $option
			$optionArray = $this->getDimensions($newWidth, $newHeight, strtolower($option));

			$optimalWidth  = $optionArray['optimalWidth'];
			$optimalHeight = $optionArray['optimalHeight'];

			// *** Resample - create image canvas of x, y size
			$this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
			imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);

			// *** if option is 'crop', then crop too
			if ($option == 'crop') {
				$this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);
			}
		}

Step 8 The Decision Tree

The more work you do now, the less you have to do when you resize. This method chooses the route to take, with the goal of getting the optimal resize width and height based on your resize option. It’ll call the appropriate method, of which we’ll be creating in the next step.

		private function getDimensions($newWidth, $newHeight, $option)
		{

		   switch ($option)
		    {
		        case 'exact':
		            $optimalWidth = $newWidth;
		            $optimalHeight= $newHeight;
		            break;
		        case 'portrait':
		            $optimalWidth = $this->getSizeByFixedHeight($newHeight);
		            $optimalHeight= $newHeight;
		            break;
		        case 'landscape':
		            $optimalWidth = $newWidth;
		            $optimalHeight= $this->getSizeByFixedWidth($newWidth);
		            break;
		        case 'auto':
		            $optionArray = $this->getSizeByAuto($newWidth, $newHeight);
					$optimalWidth = $optionArray['optimalWidth'];
					$optimalHeight = $optionArray['optimalHeight'];
		            break;
				case 'crop':
		            $optionArray = $this->getOptimalCrop($newWidth, $newHeight);
					$optimalWidth = $optionArray['optimalWidth'];
					$optimalHeight = $optionArray['optimalHeight'];
		            break;
		    }
			return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
		}

Step 9 Optimal Dimensions

We’ve already discussed what these four methods do. They’re just basic maths, really, that calculate our best fit.

		private function getSizeByFixedHeight($newHeight)
		{
		    $ratio = $this->width / $this->height;
		    $newWidth = $newHeight * $ratio;
		    return $newWidth;
		}

		private function getSizeByFixedWidth($newWidth)
		{
		    $ratio = $this->height / $this->width;
		    $newHeight = $newWidth * $ratio;
		    return $newHeight;
		}

		private function getSizeByAuto($newWidth, $newHeight)
		{
		    if ($this->height width)
		    // *** Image to be resized is wider (landscape)
		    {
		        $optimalWidth = $newWidth;
		        $optimalHeight= $this->getSizeByFixedWidth($newWidth);
		    }
		    elseif ($this->height > $this->width)
		    // *** Image to be resized is taller (portrait)
		    {
		        $optimalWidth = $this->getSizeByFixedHeight($newHeight);
		        $optimalHeight= $newHeight;
		    }
			else
		    // *** Image to be resizerd is a square
		    {
				if ($newHeight getSizeByFixedWidth($newWidth);
				} else if ($newHeight > $newWidth) {
					$optimalWidth = $this->getSizeByFixedHeight($newHeight);
				    $optimalHeight= $newHeight;
				} else {
					// *** Sqaure being resized to a square
					$optimalWidth = $newWidth;
					$optimalHeight= $newHeight;
				}
		    }

			return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
		}

		private function getOptimalCrop($newWidth, $newHeight)
		{

			$heightRatio = $this->height / $newHeight;
			$widthRatio  = $this->width /  $newWidth;

			if ($heightRatio height / $optimalRatio;
			$optimalWidth  = $this->width  / $optimalRatio;

			return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
		}

Step 10 Crop

If you opted in for a crop – that is, you’ve used the crop option, then you have one more little step. We’re going to crop the image from the
center. Cropping is a very similar process to resizing but with a couple more sizing parameters passed in.

		private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
		{
			// *** Find center - this will be used for the crop
			$cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
			$cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 );

			$crop = $this->imageResized;
			//imagedestroy($this->imageResized);

			// *** Now crop from center to exact requested size
			$this->imageResized = imagecreatetruecolor($newWidth , $newHeight);
			imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight);
		}

Step 11 Save the Image

We’re getting there; almost done. It’s now time to save the image. We pass in the path, and the image quality we would like ranging from 0-100, 100 being the best, and call the appropriate method. A couple of things to note about the image quality: JPG uses a scale of 0-100, 100 being the best. GIF images don’t have an image quality setting. PNG’s do, but they use the scale 0-9, 0 being the best. This isn’t good as we can’t expect ourselves to remember this every time we want to save an image. We do a bit of magic to standardize everything.

		public function saveImage($savePath, $imageQuality="100")
		{
			// *** Get extension
        	$extension = strrchr($savePath, '.');
        	$extension = strtolower($extension);

			switch($extension)
			{
				case '.jpg':
				case '.jpeg':
					if (imagetypes() & IMG_JPG) {
						imagejpeg($this->imageResized, $savePath, $imageQuality);
					}
		            break;

				case '.gif':
					if (imagetypes() & IMG_GIF) {
						imagegif($this->imageResized, $savePath);
					}
					break;

				case '.png':
					// *** Scale quality from 0-100 to 0-9
					$scaleQuality = round(($imageQuality/100) * 9);

					// *** Invert quality setting as 0 is best, not 9
					$invertScaleQuality = 9 - $scaleQuality;

					if (imagetypes() & IMG_PNG) {
						imagepng($this->imageResized, $savePath, $invertScaleQuality);
					}
					break;

				// ... etc

				default:
					// *** No extension - No save.
					break;
			}

			imagedestroy($this->imageResized);
		}

Now is also a good time to destroy our image resource to free up some memory. If you were to use this in production, it might also be a good idea to capture and return the result of the saved image.


Conclusion

Well that’s it, folks. Thank you for following this tutorial, I hope you find it useful. I’d appreciate your feedback, via the comments below.



Quick Tip: Cross Domain AJAX Request with YQL and jQuery

Quick Tip: Cross Domain AJAX Request with YQL and jQuery

For security reasons, we cannot make cross-domain AJAX requests with jQuery. For example, I can’t call the load() method, and pass in ‘cnn.com’. As we’d be loading in scripts and such, as well as our desired content, this would present a significant security risk. Nonetheless, there may be times when this is specifically what you require. Thanks to YQL, we can allow for this functionality rather easily!

The Script

// Accepts a url and a callback function to run.
function requestCrossDomain( site, callback ) {

	// If no url was passed, exit.
	if ( !site ) {
		alert('No site was passed.');
		return false;
	}

	// Take the provided url, and add it to a YQL query. Make sure you encode it!
	var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=?';

	// Request that YSQL string, and run a callback function.
	// Pass a defined function to prevent cache-busting.
	$.getJSON( yql, cbFunc );

	function cbFunc(data) {
	// If we have something to work with...
	if ( data.results[0] ) {
		// Strip out all script tags, for security reasons.
		// BE VERY CAREFUL. This helps, but we should do more.
		data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');

		// If the user passed a callback, and it
		// is a function, call it, and send through the data var.
		if ( typeof callback === 'function') {
			callback(data);
		}
	}
	// Else, Maybe we requested a site that doesn't exist, and nothing returned.
	else throw new Error('Nothing returned from getJSON.');
	}
}

Call the Function

requestCrossDomain('http://www.cnn.com', function(results) {
   $('#container').html(results);
});

Stripping Out the Script Tags

I had to progress rather quickly in the video, so perhaps the regular expression that strips out the <script> tags require further detail.

.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');

When we load our desired page, it’s also going to load scripts! You must be very careful when making cross domain request. It definitely helps to strip out the <script> tags, but you should do more in an actual project.

Let’s take the regular expression step by step.

<script[^>]*>

Find all open script tags; however, they could come in many forms: <script type=”text/javascript” src=”bla.js”></script> , or <script type=”text/javascript”>lots of code here…</script> . For this reason, we add a character class ( [^>]* ), which mean, “Find zero or more of anything that IS NOT a closing bracket. This will take care of the attributes and values.

[\s\S]*?

Next, we want to strip out all code, as well as any spacing. \s refers to a space. \S refers to anything that IS NOT a space. Once again, we add a * after the character class to designate that we want zero or more occurrences.

<\/script>

Finally, find the closing script tags.


Further Reading

This is only meant to provide a glimpse of how we can achieve this functionality. Only so much can be covered in a five minute video. Feel free to discuss in the comments, and you’re always encouraged to fork the source code to improve upon it!



How to Generate PDFs with PHP: New Premium Tutorial

How to Generate PDFs with PHP: New Premium Tutorial

PDFs may well be the best format for distributing documents on the web. In today’s tutorial and screencast, I’ll show you how you can generated PDFs with PHP. Help give back to Nettuts+ by becoming a Premium member!

Example PDF Created with PHP!

By subscribing and becoming a Premium member, you’ll gain access to the best tutorial, screencasts, and freebies that every Tuts sites has to offer – all for a measly $9 a month.

Join Net Premium

NETTUTS+ Screencasts and Bonus Tutorials

For those unfamiliar, the family of TUTS sites runs a premium membership service. For $9 per month, you gain access to exclusive premium tutorials, screencasts, and freebies from Nettuts+, Psdtuts+, Aetuts+, Audiotuts+, and Vectortuts+! For the price of a pizza, you’ll learn from some of the best minds in the business. Help give back to Nettuts+ by becoming a Premium member!



How to Create a PHP/MySQL Powered Forum from Scratch

How to Create a PHP/MySQL Powered Forum from Scratch

In this tutorial, we’re going to build a PHP/MySQL powered forum from scratch. This tutorial is perfect for getting used to basic PHP and database usage. Let’s dive right in!

Step 1: Creating Database Tables

It’s always a good idea to start with creating a good data model when building an application. Let’s describe our application in one sentence: We are going to make a forum which has users who create topics in various categories. Other users can post replies. As you can see, I highlighted a couple of nouns which represent our table names.

Users

  • Categories
  • Topics
  • Posts

These three objects are related to each other, so we’ll process that in our table design. Take a look at the scheme below.

Looks pretty neat, huh? Every square is a database table. All the columns are listed in it and the lines between them represent the relationships. I’ll explain them further, so it’s okay if it doesn’t make a lot of sense to you right now.

I’ll discuss each table by explaining the SQL, which I created using the scheme above. For your own scripts you can create a similar scheme and SQL too. Some editors like MySQL Workbench (the one I used) can generate .sql files too, but I would recommend learning SQL because it’s more fun to do it yourself. A SQL introduction can be found at W3Schools.

Users Table
CREATE TABLE users (
user_id 	INT(8) NOT NULL AUTO_INCREMENT,
user_name	VARCHAR(30) NOT NULL,
user_pass  	VARCHAR(255) NOT NULL,
user_email	VARCHAR(255) NOT NULL,
user_date	DATETIME NOT NULL,
user_level	INT(8) NOT NULL,
UNIQUE INDEX user_name_unique (user_name),
PRIMARY KEY (user_id)
) TYPE=INNODB;
	

The CREATE TABLE statement is used to indicate we want to create a new table, of course. The statement is followed by the name of the table and all the columns are listed between the brackets. The names of all the fields are self-explanatory, so we’ll only discuss the data types below.

user_id

“A primary key is used to uniquely identify each row in a table.”

The type of this field is INT, which means this field holds an integer. The field cannot be empty (NOT NULL) and increments which each record inserted. At the bottom of the table you can see the user_id field is declared as a primary key. A primary key is used to uniquely identify each row in a table. No two distinct rows in a table can have the same value (or combination of values) in all columns. That might be a bit unclear, so here’s a little example.

There is a user called John Doe. If another users registers with the same name, there’s a problem, because: which user is which? You can’t tell and the database can’t tell either. By using a primary key this problem is solved, because both topics are unique.

All the other tables have got primary keys too and they work the same way.

user_name

This is a text field, called a VARCHAR field in MySQL. The number between brackets is the maximum length. A user can choose a username up to 30 characters long. This field cannot be NULL. At the bottom of the table you can see this field is declared UNIQUE, which means the same username cannot be registered twice. The UNIQUE INDEX part tells the database we want to add a unique key. Then we define the name of the unique key, user_name_unique in this case. Between brackets is the field the unique key applies to, which is user_name.

user_pass

This field is equal to the user_name field, except the maximum length. Since the user password, no matter what length, is hashed with sha1(), the password will always be 40 characters long.

user_email

This field is equal to the user_pass field.

user_date

This is a field in which we’ll store the date the user registered. It’s type is DATETIME and the field cannot be NULL.

user_level

This field contains the level of the user, for example: ‘0′ for a regular user and ‘1′ for an admin. More about this later.

Categories Table

CREATE TABLE categories (
cat_id 		 	INT(8) NOT NULL AUTO_INCREMENT,
cat_name	 	VARCHAR(255) NOT NULL,
cat_description 	VARCHAR(255) NOT NULL,
UNIQUE INDEX cat_name_unique (cat_name),
PRIMARY KEY (cat_id)
) TYPE=INNODB;

These data types basically work the same way as the ones in the users table. This table also has a primary key and the name of the category must be an unique one.

Topics Table

CREATE TABLE topics (
topic_id		INT(8) NOT NULL AUTO_INCREMENT,
topic_subject  		VARCHAR(255) NOT NULL,
topic_date		DATETIME NOT NULL,
topic_cat		INT(8) NOT NULL,
topic_by		INT(8) NOT NULL,
PRIMARY KEY (topic_id)
) TYPE=INNODB;

This table is almost the same as the other tables, except for the topic_by field. That field refers to the user who created the topic. The topic_cat refers to the category the topic belongs to. We cannot force these relationships by just declaring the field. We have to let the database know this field must contain an existing user_id from the users table, or a valid cat_id from the categories table. We’ll add some relationships after I’ve discussed the posts table.

Posts Table

CREATE TABLE posts (
post_id 		INT(8) NOT NULL AUTO_INCREMENT,
post_content		TEXT NOT NULL,
post_date 		DATETIME NOT NULL,
post_topic		INT(8) NOT NULL,
post_by		INT(8) NOT NULL,
PRIMARY KEY (post_id)
) TYPE=INNODB;

This is the same as the rest of the tables; there’s also a field which refers to a user_id here: the post_by field. The post_topic field refers to the topic the post belongs to.

“A foreign key is a referential constraint between two tables. The foreign key identifies a column or a set of columns in one (referencing) table that refers to a column or set of columns in another (referenced) table.”

Now that we’ve executed these queries, we have a pretty decent data model, but the relations are still missing. Let’s start with the definition of a relationship. We’re going to use something called a foreign key. A foreign key is a referential constraint between two tables. The foreign key identifies a column or a set of columns in one (referencing) table that refers to a column or set of columns in another (referenced) table. Some conditions:

  • The column in the referencing table the foreign key refers to must be a primary key
  • The values that are referred to must exist in the referenced table

By adding foreign keys the information is linked together which is very important for database normalization. Now you know what a foreign key is and why we’re using them. It’s time to add them to the tables we’ve already made by using the ALTER statement, which can be used to change an already existing table.

We’ll link the topics to the categories first:

ALTER TABLE topics ADD FOREIGN KEY(topic_cat) REFERENCES categories(cat_id) ON DELETE CASCADE ON UPDATE CASCADE;

The last part of the query already says what happens. When a category gets deleted from the database, all the topics will be deleted too. If the cat_id of a category changes, every topic will be updated too. That’s what the ON UPDATE CASCADE part is for. Of course, you can reverse this to protect your data, so that you can’t delete a category as long as it still has topics linked to it. If you would want to do that, you could replace the ‘ON DELETE CASCADE’ part with ‘ON DELETE RESTRICT’. There is also SET NULL and NO ACTION, which speak for themselves.

Every topic is linked to a category now. Let’s link the topics to the user who creates one.

ALTER TABLE topics ADD FOREIGN KEY(topic_by) REFERENCES users(user_id) ON DELETE RESTRICT ON UPDATE CASCADE;

This foreign key is the same as the previous one, but there is one difference: the user can’t be deleted as long as there are still topics with the user id of the user. We don’t use CASCADE here because there might be valuable information in our topics. We wouldn’t want that information to get deleted if someone decides to delete their account. To still give users the opportunity to delete their account, you could build some feature that anonymizes all their topics and then delete their account. Unfortunately, that is beyond the scope of this tutorial.


Link the posts to the topics:

ALTER TABLE posts ADD FOREIGN KEY(post_topic) REFERENCES topics(topic_id) ON DELETE CASCADE ON UPDATE CASCADE;

And finally, link each post to the user who made it:

ALTER TABLE posts ADD FOREIGN KEY(post_by) REFERENCES users(user_id) ON DELETE RESTRICT ON UPDATE CASCADE;

That’s the database part! It was quite a lot of work, but the result, a great data model, is definitely worth it.


Step 2: Introduction to the Header/Footer System

Each page of our forum needs a few basic things, like a doctype and some markup. That’s why we’ll include a header.php file at the top of each page, and a footer.php at the bottom. The header.php contains a doctype, a link to the stylesheet and some important information about the forum, such as the title tag and metatags.

header.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="nl" lang="nl">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<meta name="description" content="A short description." />
	<meta name="keywords" content="put, keywords, here" />
	<title>PHP-MySQL forum</title>
	<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<h1>My forum</h1>
	<div id="wrapper">
	<div id="menu">
		<a class="item" href="/forum/index.php">Home</a> -
		<a class="item" href="/forum/create_topic.php">Create a topic</a> -
		<a class="item" href="/forum/create_cat.php">Create a category</a>

		<div id="userbar">
		<div id="userbar">Hello Example. Not you? Log out.</div>
	</div>
		<div id="content">
	

The wrapper div will be used to make it easier to style the entire page. The menu div obviously contains a menu with links to pages we still have to create, but it helps to see where we’re going a little bit. The userbar div is going to be used for a small top bar which contains some information like the username and a link to the logout page. The content page holds the actual content of the page, obviously.

The attentive reader might have already noticed we’re missing some things. There is no </body> or </html> tag. They’re in the footer.php page, as you can see below.

</div><!-- content -->
</div><!-- wrapper -->
<div id="footer">Created for Nettuts+</div>
</body>
</html>
	

When we include a header and a footer on each page the rest of the page get embedded between the header and the footer. This method has got some advantages. First and foremost, everything will be styled correctly. A short example:

<?php
$error = false;
if($error = false)
{
 	//the beautifully styled content, everything looks good
 	echo '<div id="content">some text</div>';
}
else
{
 	//bad looking, unstyled error :-(
}
?>
	

As you can see, a page without errors will result in a nice page with the content. But if there’s an error, everything looks really ugly; so that’s why it’s better to make sure not only real content is styled correctly, but also the errors we might get.

Another advantage is the possibility of making quick changes. You can see for yourself by editing the text in footer.php when you’ve finished this tutorial; you’ll notice that the footer changes on every page immediately. Finally, we add a stylesheet which provides us with some basic markup – nothing too fancy.

body {
	background-color: #4E4E4E;
	text-align: center;			/* make sure IE centers the page too */
}

#wrapper {
	width: 900px;
	margin: 0 auto; 			/* center the page */
}

#content {
	background-color: #fff;
	border: 1px solid #000;
	float: left;
	font-family: Arial;
	padding: 20px 30px;
	text-align: left;
	width: 100%;				/* fill up the entire div */
}

#menu {
	float: left;
	border: 1px solid #000;
	border-bottom: none;		/* avoid a double border */
	clear: both;				/* clear:both makes sure the content div doesn't float next to this one but stays under it */
	width:100%;
	height:20px;
	padding: 0 30px;
	background-color: #FFF;
	text-align: left;
	font-size: 85%;
}

#menu a:hover {
	background-color: #009FC1;
}

#userbar {
	background-color: #fff;
	float: right;
	width: 250px;
}

#footer {
	clear: both;
}

/* begin table styles */
table {
	border-collapse: collapse;
	width: 100%;
}

table a {
	color: #000;
}

table a:hover {
	color:#373737;
	text-decoration: none;
}

th {
	background-color: #B40E1F;
	color: #F0F0F0;
}

td {
	padding: 5px;
}

/* Begin font styles */
h1, #footer {
	font-family: Arial;
	color: #F1F3F1;
}

h3 {margin: 0; padding: 0;}

/* Menu styles */
.item {
	background-color: #00728B;
	border: 1px solid #032472;
	color: #FFF;
	font-family: Arial;
	padding: 3px;
	text-decoration: none;
}

.leftpart {
	width: 70%;
}

.rightpart {
	width: 30%;
}

.small {
	font-size: 75%;
	color: #373737;
}
#footer {
	font-size: 65%;
	padding: 3px 0 0 0;
}

.topic-post {
	height: 100px;
	overflow: auto;
}

.post-content {
	padding: 30px;
}

textarea {
	width: 500px;
	height: 200px;
}
	

Step 3: Getting Ready for Action

Before we can read anything from our database, we need a connection. That’s what connect.php is for. We’ll include it in every file we are going to create.

<?php
//connect.php
$server	= 'localhost';
$username	= 'usernamehere';
$password	= 'passwordhere';
$database	= 'databasenamehere';

if(!mysql_connect($server, $username,  $password))
{
 	exit('Error: could not establish database connection');
}
if(!mysql_select_db($database)
{
 	exit('Error: could not select the database');
}
?>
	

Simply replace the default values of the variables at the top of the page with your own date, save the file and you’re good to go!


Step 4: Displaying the Forum Overview

Since we’re just started with some basic techniques, we’re going to make a simplified version of the forum overview for now.

<?php
//create_cat.php
include 'connect.php';
include 'header.php';

echo '<tr>';
	echo '<td class="leftpart">';
		echo '<h3><a href="category.php?id=">Category name</a></h3> Category description goes here';
	echo '</td>';
	echo '<td class="rightpart">';
			echo '<a href="topic.php?id=">Topic subject</a> at 10-10';
	echo '</td>';
echo '</tr>';
include 'footer.php';
?>
	

There you have it: a nice and clean overview. We’ll be updating this page throughout the tutorial so that it becomes more like the end result, step by step!


Step 5: Signing up a User

Let’s start by making a simple HTML form so that a new user can register.

A PHP page is needed to process the form. We’re going to use a $_SERVER variable. The $_SERVER variable is an array with values that are automatically set with each request. One of the values of the $_SERVER array is ‘REQUEST_METHOD’. When a page is requested with GET, this variable will hold the value ‘GET’. When a page is requested via POST, it will hold the value ‘POST’. We can use this value to check if a form has been posted. See the signup.php page below.

<?php
//signup.php
include 'connect.php';
include 'header.php';

echo '<h3>Sign up</h3>';

if($_SERVER['REQUEST_METHOD'] != 'POST')
{
    /*the form hasn't been posted yet, display it
	  note that the action="" will cause the form to post to the same page it is on */
    echo '<form method="post" action="">
 	 	Username: <input type="text" name="user_name" />
 		Password: <input type="password" name="user_pass">
		Password again: <input type="password" name="user_pass_check">
		E-mail: <input type="email" name="user_email">
 		<input type="submit" value="Add category" />
 	 </form>';
}
else
{
    /* so, the form has been posted, we'll process the data in three steps:
		1.	Check the data
		2.	Let the user refill the wrong fields (if necessary)
		3.	Save the data
	*/
	$errors = array(); /* declare the array for later use */

	if(isset($_POST['user_name']))
	{
		//the user name exists
		if(!ctype_alnum($_POST['user_name']))
		{
			$errors[] = 'The username can only contain letters and digits.';
		}
		if(strlen($_POST['user_name']) > 30)
		{
			$errors[] = 'The username cannot be longer than 30 characters.';
		}
	}
	else
	{
		$errors[] = 'The username field must not be empty.';
	}

	if(isset($_POST['user_pass']))
	{
		if($_POST['user_pass'] != $_POST['user_pass_check'])
		{
			$errors[] = 'The two passwords did not match.';
		}
	}
	else
	{
		$errors[] = 'The password field cannot be empty.';
	}

	if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/
	{
		echo 'Uh-oh.. a couple of fields are not filled in correctly..';
		echo '<ul>';
		foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */
		{
			echo '<li>' . $value . '</li>'; /* this generates a nice error list */
		}
		echo '</ul>';
	}
	else
	{
		//the form has been posted without, so save it
		//notice the use of mysql_real_escape_string, keep everything safe!
		//also notice the sha1 function which hashes the password
		$sql = "INSERT INTO
					users(user_name, user_pass, user_email ,user_date, user_level)
				VALUES('" . mysql_real_escape_string($_POST['user_name']) . "',
					   '" . sha1($_POST['user_pass']) . "',
					   '" . mysql_real_escape_string($_POST['user_email']) . "',
						NOW(),
						0)";

		$result = mysql_query($sql);
		if(!$result)
		{
			//something went wrong, display the error
			echo 'Something went wrong while registering. Please try again later.';
			//echo mysql_error(); //debugging purposes, uncomment when needed
		}
		else
		{
			echo 'Successfully registered. You can now <a href="signin.php">sign in</a> and start posting! :-) ';
		}
	}
}

include 'footer.php';
?>
	

A lot of explanation is in the comments I made in the file, so be sure to check them out. The processing of the data takes place in three parts:

  • Validating the data
  • If the data is not valid, show the form again
  • If the data is valid, save the record in the database

The PHP part is quite self-explanatory. The SQL-query however probably needs a little more explanation.

INSERT INTO
       users(user_name, user_pass, user_email ,user_date, user_level)
VALUES('" . mysql_real_escape_string($_POST['user_name']) . "',
       '" . sha1($_POST['user_pass']) . "',
       '" . mysql_real_escape_string($_POST['user_email']) . "',
       NOW(),
       0);
	

On line 1 we have the INSERT INTO statement which speaks for itself. The table name is specified on the second line. The words between the brackets represent the columns in which we want to insert the data. The VALUES statement tells the database we’re done declaring column names and it’s time to specify the values. There is something new here: mysql_real_escape_string. The function escapes special characters in an unescaped string , so that it is safe to place it in a query. This function MUST always be used, with very few exceptions. There are too many scripts that don’t use it and can be hacked real easy. Don’t take the risk, use mysql_real_escape_string().

“Never insert a plain password as-is. You MUST always encrypt it.”

Also, you can see that the function sha1() is used to encrypt the user’s password. This is also a very important thing to remember. Never insert a plain password as-is. You MUST always encrypt it. Imagine a hacker who somehow manages to get access to your database. If he sees all the plain-text passwords he could log into any (admin) account he wants. If the password columns contain sha1 strings he has to crack them first which is almost impossible.

Note: it’s also possible to use md5(), I always use sha1() because benchmarks have proved it’s a tiny bit faster, not much though. You can replace sha1 with md5 if you like.

If the signup process was successful, you should see something like this:

Try refreshing your phpMyAdmin screen, a new record should be visible in the users table.


Step 6: Adding Authentication and User Levels

An important aspect of a forum is the difference between regular users and admins/moderators. Since this is a small forum and adding features like adding new moderators and stuff would take way too much time, we’ll focus on the login process and create some admin features like creating new categories and closing a thread.

Now that you’ve completed the previous step, we’re going to make your freshly created account an admin account. In phpMyAdmin, click on the users table, and then ‘Browse’. Your account will probably pop up right away. Click the edit icon and change the value of the user_level field from 0 to 1. That’s it for now. You won’t notice any difference in our application immediately, but when we’ve added the admin features a normal account and your account will have different capabilities.

The sign-in process works the following way:

  • A visitor enters user data and submits the form
  • If the username and password are correct, we can start a session
  • If the username and password are incorrect, we show the form again with a message

The signin.php file is below. Don’t think I’m not explaining what I’m doing, but check out the comments in the file. It’s much easier to understand that way.

<?php
//signin.php
include 'connect.php';
include 'header.php';

echo '<h3>Sign in</h3>';

//first, check if the user is already signed in. If that is the case, there is no need to display this page
if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
{
	echo 'You are already signed in, you can <a href="signout.php">sign out</a> if you want.';
}
else
{
	if($_SERVER['REQUEST_METHOD'] != 'POST')
	{
		/*the form hasn't been posted yet, display it
		  note that the action="" will cause the form to post to the same page it is on */
		echo '<form method="post" action="">
			Username: <input type="text" name="user_name" />
			Password: <input type="password" name="user_pass">
			<input type="submit" value="Sign in" />
		 </form>';
	}
	else
	{
		/* so, the form has been posted, we'll process the data in three steps:
			1.	Check the data
			2.	Let the user refill the wrong fields (if necessary)
			3.	Varify if the data is correct and return the correct response
		*/
		$errors = array(); /* declare the array for later use */

		if(!isset($_POST['user_name']))
		{
			$errors[] = 'The username field must not be empty.';
		}

		if(!isset($_POST['user_pass']))
		{
			$errors[] = 'The password field must not be empty.';
		}

		if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/
		{
			echo 'Uh-oh.. a couple of fields are not filled in correctly..';
			echo '<ul>';
			foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */
			{
				echo '<li>' . $value . '</li>'; /* this generates a nice error list */
			}
			echo '</ul>';
		}
		else
		{
			//the form has been posted without errors, so save it
			//notice the use of mysql_real_escape_string, keep everything safe!
			//also notice the sha1 function which hashes the password
			$sql = "SELECT
						user_id,
						user_name,
						user_level
					FROM
						users
					WHERE
						user_name = '" . mysql_real_escape_string($_POST['user_name']) . "'
					AND
						user_pass = '" . sha1($_POST['user_pass']) . "'";

			$result = mysql_query($sql);
			if(!$result)
			{
				//something went wrong, display the error
				echo 'Something went wrong while signing in. Please try again later.';
				//echo mysql_error(); //debugging purposes, uncomment when needed
			}
			else
			{
				//the query was successfully executed, there are 2 possibilities
				//1. the query returned data, the user can be signed in
				//2. the query returned an empty result set, the credentials were wrong
				if(mysql_num_rows($result) == 0)
				{
					echo 'You have supplied a wrong user/password combination. Please try again.';
				}
				else
				{
					//set the $_SESSION['signed_in'] variable to TRUE
					$_SESSION['signed_in'] = true;

					//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
					while($row = mysql_fetch_assoc($result))
					{
						$_SESSION['user_id'] 	= $row['user_id'];
						$_SESSION['user_name'] 	= $row['user_name'];
						$_SESSION['user_level'] = $row['user_level'];
					}

					echo 'Welcome, ' . $_SESSION['user_name'] . '. <a href="index.php">Proceed to the forum overview</a>.';
				}
			}
		}
	}
}

include 'footer.php';
?>
	

This is the query that’s in the signin.php file:

SELECT
	user_id,
	user_name,
	user_level
FROM
	users
WHERE
	user_name = '" . mysql_real_escape_string($_POST['user_name']) . "'
AND
	user_pass = '" . sha1($_POST['user_pass'])
	

It’s obvious we need a check to tell if the supplied credentials belong to an existing user. A lot of scripts retrieve the password from the database and compare it using PHP. If we do this directly via SQL the password will be stored in the database once during registration and never leave it again. This is safer, because all the real action happens in the database layer and not in our application.

If the user is signed in successfully, we’re doing a few things:

<?php
//set the $_SESSION['signed_in'] variable to TRUE
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
while($row = mysql_fetch_assoc($result))
{
 	$_SESSION['user_id'] = $row['user_id'];
 	$_SESSION['user_name'] = $row['user_name'];
}
?>
	

First, we set the ’signed_in’ $_SESSION var to true, so we can use it on other pages to make sure the user is signed in. We also put the username and user id in the $_SESSION variable for usage on a different page. Finally, we display a link to the forum overview so the user can get started right away.

Of course signing in requires another function, signing out! The sign-out process is actually a lot easier than the sign-in process. Because all the information about the user is stored in $_SESSION variables, all we have to do is unset them and display a message.

Now that we’ve set the $_SESSION variables, we can determine if someone is signed in. Let’s make a last simple change to header.php:

Replace:

<div id="userbar">Hello Example. Not you? Log out.</div>
	

With:

<?php
<div id="userbar">
 	if($_SESSION['signed_in'])
 	{
 	 	echo 'Hello' . $_SESSION['user_name'] . '. Not you? <a href="signout.php">Sign out</a>';
 	}
 	else
 	{
 		echo '<a href="signin.php">Sign in</a> or <a href="sign up">create an account</a>.';
 	}
</div>
	

If a user is signed in, he will see his or her name displayed on the front page with a link to the signout page. Our authentication is done! By now our forum should look like this:


Step 7: Creating a Category

We want to create categories so let’s start with making a form.

<form method="post" action="">
 	Category name: <input type="text" name="cat_name" />
 	Category description: <textarea name="cat_description" /></textarea>
	<input type="submit" value="Add category" />
 </form>
	

This step looks a lot like Step 4 (Signing up a user’), so I’m not going to do an in-depth explanation here. If you followed all the steps you should be able to understand this somewhat quickly.

<?php
//create_cat.php
include 'connect.php';

if($_SERVER['REQUEST_METHOD'] != 'POST')
{
    //the form hasn't been posted yet, display it
    echo '<form method='post' action=''>
 	 	Category name: <input type='text' name='cat_name' />
 		Category description: <textarea name='cat_description' /></textarea>
 		<input type='submit' value='Add category' />
 	 </form>';
}
else
{
    //the form has been posted, so save it
    $sql = ìINSERT INTO categories(cat_name, cat_description)
 	   VALUES('' . mysql_real_escape_string($_POST['cat_name']) . ì',
 		     '' . mysql_real_escape_string($_POST['cat_description']) . ì')';
    $result = mysql_query($sql);
    if(!$result)
    {
        //something went wrong, display the error
        echo 'Error' . mysql_error();
    }
    else
    {
        echo 'New category successfully added.';
    }
}
?>
	

As you can see, we’ve started the script with the $_SERVER check, after checking if the user has admin rights, which is required for creating a category. The form gets displayed if it hasn’t been submitted already. If it has, the values are saved. Once again, a SQL query is prepared and then executed.


Step 8: Adding Categories to index.php

We’ve created some categories, so now we’re able to display them on the front page. Let’s add the following query to the content area of index.php.

SELECT
 	categories.cat_id,
	categories.cat_name,
 	categories.cat_description,
FROM
 	categories
	

This query selects all categories and their names and descriptions from the categories table. We only need a bit of PHP to display the results. If we add that part just like we did in the previous steps, the code will look like this.

<?php
//create_cat.php
include 'connect.php';
include 'header.php';

$sql = "SELECT
			cat_id,
			cat_name,
			cat_description,
		FROM
			categories";

$result = mysql_query($sql);

if(!$result)
{
	echo 'The categories could not be displayed, please try again later.';
}
else
{
	if(mysql_num_rows($result) == 0)
	{
		echo 'No categories defined yet.';
	}
	else
	{
		//prepare the table
		echo '<table border="1">
			  <tr>
				<th>Category</th>
				<th>Last topic</th>
			  </tr>';	

		while($row = mysql_fetch_assoc($result))
		{
			echo '<tr>';
				echo '<td class="leftpart">';
					echo '<h3><a href="category.php?id">' . $row['cat_name'] . '</a></h3>' . $row['cat_description'];
				echo '</td>';
				echo '<td class="rightpart">';
							echo '<a href="topic.php?id=">Topic subject</a> at 10-10';
				echo '</td>';
			echo '</tr>';
		}
	}
}

include 'footer.php';
?>
	

Notice how we’re using the cat_id to create links to category.php. All the links to this page will look like this: category.php?cat_id=x, where x can be any numeric value. This may be new to you. We can check the url with PHP for $_GET values. For example, we have this link:

category.php?cat_id=23
	

The statement echo $_GET[ëcat_id’];’ will display ‘23′. In the next few steps we’ll use this value to retrieve the topics when viewing a single category, but topics can’t be viewed if we haven’t created them yet. So let’s create some topics!


Step 9: Creating a Topic

In this step, we’re combining the techniques we learned in the previous steps. We’re checking if a user is signed in, we’ll use an input query to create the topic and create some basic HTML forms.

The structure of create_topic.php can hardly be explained in a list or something, so I rewrote it in pseudo-code.

<?php
if(user is signed in)
{
	//the user is not signed in
}
else
{
	//the user is signed in
	if(form has not been posted)
	{
		//show form
	}
	else
	{
		//process form
	}
}
?>
	

Here’s the real code of this part of our forum, check the explanations below the code to see what it’s doing.

<?php
//create_cat.php
include 'connect.php';
include 'header.php';

echo '<h2>Create a topic</h2>';
if($_SESSION['signed_in'] == false)
{
	//the user is not signed in
	echo 'Sorry, you have to be <a href="/forum/signin.php">signed in</a> to create a topic.';
}
else
{
	//the user is signed in
	if($_SERVER['REQUEST_METHOD'] != 'POST')
	{
		//the form hasn't been posted yet, display it
		//retrieve the categories from the database for use in the dropdown
		$sql = "SELECT
					cat_id,
					cat_name,
					cat_description
				FROM
					categories";

		$result = mysql_query($sql);

		if(!$result)
		{
			//the query failed, uh-oh :-(
			echo 'Error while selecting from database. Please try again later.';
		}
		else
		{
			if(mysql_num_rows($result) == 0)
			{
				//there are no categories, so a topic can't be posted
				if($_SESSION['user_level'] == 1)
				{
					echo 'You have not created categories yet.';
				}
				else
				{
					echo 'Before you can post a topic, you must wait for an admin to create some categories.';
				}
			}
			else
			{

				echo '<form method="post" action="">
					Subject: <input type="text" name="topic_subject" />
					Category:'; 

				echo '<select name="topic_cat">';
					while($row = mysql_fetch_assoc($result))
					{
						echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
					}
				echo '</select>';	

				echo 'Message: <textarea name="post_content" /></textarea>
					<input type="submit" value="Create topic" />
				 </form>';
			}
		}
	}
	else
	{
		//start the transaction
		$query  = "BEGIN WORK;";
		$result = mysql_query($query);

		if(!$result)
		{
			//Damn! the query failed, quit
			echo 'An error occured while creating your topic. Please try again later.';
		}
		else
		{

			//the form has been posted, so save it
			//insert the topic into the topics table first, then we'll save the post into the posts table
			$sql = "INSERT INTO
						topics(topic_subject,
							   topic_date,
							   topic_cat,
							   topic_by)
				   VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "',
							   NOW(),
							   " . mysql_real_escape_string($_POST['topic_cat']) . ",
							   " . $_SESSION['user_id'] . "
							   )";

			$result = mysql_query($sql);
			if(!$result)
			{
				//something went wrong, display the error
				echo 'An error occured while inserting your data. Please try again later.' . mysql_error();
				$sql = "ROLLBACK;";
				$result = mysql_query($sql);
			}
			else
			{
				//the first query worked, now start the second, posts query
				//retrieve the id of the freshly created topic for usage in the posts query
				$topicid = mysql_insert_id();

				$sql = "INSERT INTO
							posts(post_content,
								  post_date,
								  post_topic,
								  post_by)
						VALUES
							('" . mysql_real_escape_string($_POST['post_content']) . "',
								  NOW(),
								  " . $topicid . ",
								  " . $_SESSION['user_id'] . "
							)";
				$result = mysql_query($sql);

				if(!$result)
				{
					//something went wrong, display the error
					echo 'An error occured while inserting your post. Please try again later.' . mysql_error();
					$sql = "ROLLBACK;";
					$result = mysql_query($sql);
				}
				else
				{
					$sql = "COMMIT;";
					$result = mysql_query($sql);

					//after a lot of work, the query succeeded!
					echo 'You have successfully created <a href="topic.php?id='. $topicid . '">your new topic</a>.';
				}
			}
		}
	}
}

include 'footer.php';
?>
	

I’ll discuss this page in two parts, showing the form and processing the form.

Showing the form
We’re starting with a simple HTML form. There is actually something special here, because we use a dropdown. This dropdown is filled with data from the database, using this query:

SELECT
 	cat_id,
 	cat_name,
 	cat_description
FROM
 	categories
	

That’s the only potentially confusing part here; it’s quite a piece of code, as you can see when looking at the create_topic.php file at the bottom of this step.

Processing the form

The process of saving the topic consists of two parts: saving the topic in the topics table and saving the first post in the posts table. This requires something quite advanced that goes a bit beyond the scope of this tutorial. It’s called a transaction, which basically means that we start by executing the start command and then rollback when there are database errors and commit when everything went well. More about transactions.

<?php
//start the transaction
$query  = "BEGIN WORK;";
$result = mysql_query($query);
//stop the transaction
$sql = "ROLLBACK;";
$result = mysql_query($sql);
//commit the transaction
$sql = "COMMIT;";
$result = mysql_query($sql);
?>
	

The first query being used to save the data is the topic creation query, which looks like this:

INSERT INTO
	topics(topic_subject,
               topic_date,
               topic_cat,
               topic_by)
VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "',
       NOW(),
       " . mysql_real_escape_string($_POST['topic_cat']) . ",
       " . $_SESSION['user_id'] . ")
	

At first the fields are defined, then the values to be inserted. We’ve seen the first one before, it’s just a string which is made safe by using mysql_real_escape_string(). The second value, NOW(), is a SQL function for the current time. The third value, however, is a value we haven’t seen before. It refers to a (valid) id of a category. The last value refers to an (existing) user_id which is, in this case, the value of $_SESSION[ëuser_id’]. This variable was declared during the sign in process.

If the query executed without errors we proceed to the second query. Remember we are still doing a transaction here. If we would’ve got errors we would have used the ROLLBACK command.

INSERT INTO
        posts(post_content,
        post_date,
        post_topic,
        post_by)
VALUES
        ('" . mysql_real_escape_string($_POST['post_content']) . "',
         NOW(),
         " . $topicid . ",
         " . $_SESSION['user_id'] . ")
	

The first thing we do in this code is use mysql_insert_id() to retrieve the latest generated id from the topic_id field in the topics table. As you may remember from the first steps of this tutorial, the id is generated in the database using auto_increment.

Then the post is inserted into the posts table. This query looks a lot like the topics query. The only difference is that this post refers to the topic and the topic referred to a category. From the start, we decided to create a good data model and here is the result: a nice hierarchical structure.


Step 10: Category View

We’re going to make an overview page for a single category. We’ve just created a category, it would be handy to be able to view all the topics in it. First, create a page called category.php.

A short list of the things we need:

Needed for displaying the category

  • cat_name
  • cat_description

Needed for displaying all the topics

  • topic_id
  • topic_subject
  • topic_date
  • topic_cat

Let’s create the two SQL queries that retrieve exactly this data from the database.

SELECT
    cat_id,
    cat_name,
    cat_description
FROM
    categories
WHERE
    cat_id = " . mysql_real_escape_string($_GET['id'])
	

The query above selects all the categories from the database.

SELECT
    topic_id,
    topic_subject,
    topic_date,
    topic_cat
FROM
    topics
WHERE
    topic_cat = " . mysql_real_escape_string($_GET['id'])
	

The query above is executed in the while loop in which we echo the categories. By doing it this way, we’ll see all the categories and the latest topic for each of them.
The complete code of category.php will be the following:

<?php
//create_cat.php
include 'connect.php';
include 'header.php';

//first select the category based on $_GET['cat_id']
$sql = "SELECT
			cat_id,
			cat_name,
			cat_description
		FROM
			categories
		WHERE
			cat_id = " . mysql_real_escape_string($_GET['id']);

$result = mysql_query($sql);

if(!$result)
{
	echo 'The category could not be displayed, please try again later.' . mysql_error();
}
else
{
	if(mysql_num_rows($result) == 0)
	{
		echo 'This category does not exist.';
	}
	else
	{
		//display category data
		while($row = mysql_fetch_assoc($result))
		{
			echo '<h2>Topics in ′' . $row['cat_name'] . '′ category</h2>';
		}

		//do a query for the topics
		$sql = "SELECT
					topic_id,
					topic_subject,
					topic_date,
					topic_cat
				FROM
					topics
				WHERE
					topic_cat = " . mysql_real_escape_string($_GET['id']);

		$result = mysql_query($sql);

		if(!$result)
		{
			echo 'The topics could not be displayed, please try again later.';
		}
		else
		{
			if(mysql_num_rows($result) == 0)
			{
				echo 'There are no topics in this category yet.';
			}
			else
			{
				//prepare the table
				echo '<table border="1">
					  <tr>
						<th>Topic</th>
						<th>Created at</th>
					  </tr>';	

				while($row = mysql_fetch_assoc($result))
				{
					echo '<tr>';
						echo '<td class="leftpart">';
							echo '<h3><a href="topic.php?id=' . $row['topic_id'] . '">' . $row['topic_subject'] . '</a><h3>';
						echo '</td>';
						echo '<td class="rightpart">';
							echo date('d-m-Y', strtotime($row['topic_date']));
						echo '</td>';
					echo '</tr>';
				}
			}
		}
	}
}

include 'footer.php';
?>
	

And here is the final result of our categories page:


Step 11: Topic View

The SQL queries in this step are complicated ones. The PHP-part is all stuff that you’ve seen before. Let’s take a look at the queries. The first one retrieves basic information about the topic:

SELECT
    topic_id,
    topic_subject
FROM
    topics
WHERE
    topics.topic_id = " . mysql_real_escape_string($_GET['id'])
	

This information is displayed in the head of the table we will use to display all the data. Next, we retrieve all the posts in this topic from the database. The following query gives us exactly what we need:

SELECT
    posts.post_topic,
    posts.post_content,
    posts.post_date,
    posts.post_by,
    users.user_id,
    users.user_name
FROM
    posts
LEFT JOIN
    users
ON
    posts.post_by = users.user_id
WHERE
    posts.post_topic = " . mysql_real_escape_string($_GET['id'])
	

This time, we want information from the users and the posts table – so we use the LEFT JOIN again. The condition is: the user id should be the same as the post_by field. This way we can show the username of the user who replied at each post.

The final topic view looks like this:


Step 12: Adding a Reply

Let’s create the last missing part of this forum, the possibility to add a reply. We’ll start by creating a form:

<form method="post" action="reply.php?id=5">
    <textarea name="reply-content"></textarea>
    <input type="submit" value="Submit reply" />
</form>
	

The complete reply.php code looks like this.

<?php
//create_cat.php
include 'connect.php';
include 'header.php';

if($_SERVER['REQUEST_METHOD'] != 'POST')
{
	//someone is calling the file directly, which we don't want
	echo 'This file cannot be called directly.';
}
else
{
	//check for sign in status
	if(!$_SESSION['signed_in'])
	{
		echo 'You must be signed in to post a reply.';
	}
	else
	{
		//a real user posted a real reply
		$sql = "INSERT INTO
					posts(post_content,
						  post_date,
						  post_topic,
						  post_by)
				VALUES ('" . $_POST['reply-content'] . "',
						NOW(),
						" . mysql_real_escape_string($_GET['id']) . ",
						" . $_SESSION['user_id'] . ")";

		$result = mysql_query($sql);

		if(!$result)
		{
			echo 'Your reply has not been saved, please try again later.';
		}
		else
		{
			echo 'Your reply has been saved, check out <a href="topic.php?id=' . htmlentities($_GET['id']) . '">the topic</a>.';
		}
	}
}

include 'footer.php';
?>
	

The comments in the code pretty much detail what’s happening. We’re checking for a real user and then inserting the post into the database.


Finishing Up

Now that you’ve finished this tutorial, you should have a much better understanding of what it takes to build a forum. I hope my explanations were clear enough! Thanks again for reading.



Winners Announced: CodeCanyon Competition

Winners Announced: CodeCanyon Competition

For the entire month of February, developers were encouraged to submit their best scripts and components to CodeCanyon. With over $6200 worth of prizes to win, it was a battle consisting of many high level items. However, the competition has since concluded, and after two weeks of deliberating, the reviewers and I have made our choices for the top three spots!

Grand Prize Winner: Sitebase

Advanced Backup System

“This script is a must have for every webdeveloper/webmaster that want to save some time. Advanced Backup System or Abs helps you with tasks as backing up files, backing up databases and deploy new version to a server.”

Prizes Awarded

  1. 1 Dedicated Virtual Box (Rage) from Media Temple ($1200 value)
  2. 1 32 gigabyte iPod Touch ($299 value) (Ultimate TechSmith Package)
  3. 1 copy of Camtasia Studio for Mac or PC ($299 value) (Ultimate TechSmith Package)
  4. 1 copy of Camtasia Studio 6: The Definitive Guide ($39.95 value) (Ultimate TechSmith Package)
  5. 1 Logitech QuickCam Communicate Deluxe PC Webcam ($99 value) (Ultimate TechSmith Package)
  6. 1 Audio Technica USB Studio Condenser Microphone ($149 value) (Ultimate TechSmith Package)
  7. $100 Envato credit (Can be used across all of the marketplaces)
  8. $200 cash
  9. 1 MediaTemple Gift Card – 1 year of hosting, 1 domain name, Up to 5 websites. ($95 value)
  10. $25 Amazon Gift Card
  11. 1 year Tuts Plus membership – ($78 value)
  12. 1 Wufoo Subscription – 1 year ($288 value)
  13. 1 Formspring Pro Subscription – 1 year ($348 value)
  14. 1 Surreal CMS Subscription – 1 year ($275 value)
  15. 1 Personal TypeKit subscription – 1 year ($300 value)
  16. 1 Myows Paid AccountFREE for life
  17. 1 Rockable Press Book of your Choice ($29 value)
  18. 1 copy of Snippet (mac app) ($13 value)
  19. 1 copy of jQuery UI 1.7 from Packt Publishing ($40.49 value)
  20. 1 copy of Magento Beginner’s Guide from Packt Publishing ($35.99 value)
  21. 1 copy of Object-Oriented JavaScript from Packt Publishing ($35.99 value)
  22. 1 copy of jQuery Cookbook from O’Reilly Publishing ($34.99 value)
  23. 1 Threadsy Invite
  24. You will be featured on the front page of CodeCanyon as both the featured author and the featured item of the week!
  25. Your item will be included in a collection of the three winning submissions, and will be promoted on the front page of CodeCanyon
  26. As an Envato marketplace author, you’ll earn 40-70% of every sale!

2nd Place: 23andwalnut

Clientele

Clientele is a secure client portal for your business. Each client is given their own account that provides a dashboard for them to monitor project status, upload/download documents and files related to their projects, and communicate with you. Using this portal can significantly reduce the amount of admin work you do, by providing a one stop shop for clients to get details about their projects.

Prizes Awarded

  1. 1 year Tuts Plus membership – ($78 value)
  2. $50 Envato credit
  3. 1 Personal TypeKit subscription – 1 year ($300 value)
  4. 1 Surreal CMS Subscription – 1 year ($275 value)
  5. 1 Wufoo Subscription – 1 year ($288 value)
  6. 1 Myows Paid AccountFREE for life
  7. 1 Rockable Press Book of your Choice ($29 value)
  8. 1 copy of Snippet (mac app) ($13 value)
  9. 1 Threadsy Invite
  10. Your item will be included in a collection of the three winning submissions, and will be promoted on the front page of CodeCanyon
  11. As an Envato marketplace author, you’ll earn 40-70% of every sale!

3rd Place : aeroalquimia

Sexy Slider

“SexySlider is a JQuery plugin that lets you easily create powerful javascript Sliders with very nice transition effects. Enhance your website by adding a unique and attractive slider!”

Prizes Awarded

  1. 1 year Tuts Plus membership – ($78 value)
  2. $50 Envato credit
  3. 1 Personal TypeKit subscription – 1 year ($300 value)
  4. 1 Surreal CMS Subscription – 1 year ($275 value)
  5. 1 Wufoo Subscription – 1 year ($288 value)
  6. 1 Myows Paid AccountFREE for life
  7. 1 Rockable Press Book of your Choice ($29 value)
  8. 1 copy of Snippet (mac app) ($13 value)
  9. 1 Threadsy Invite
  10. Your item will be included in a collection of the three winning submissions, and will be promoted on the front page of CodeCanyon
  11. As an Envato marketplace author, you’ll earn 40-70% of every sale!

Honorable Mentions

We had an extremely difficult time choosing only three winners, when there were so many top level submissions! Here are a sampling of some the other front-runners!

A huge thanks goes out to everyone who entered. Even if you didn’t win, you’re now earning 40-70% of every sale of your item. Thanks again to our incredible sponsors for helping us out. So until next time…



IE9 May Actually Be a Fantastic Browser

IE9 May Actually Be a Fantastic Browser

Today, as part of MIX 2010, some exciting updates were released on the progress of Internet Explorer 9. The IE team is implementing some incredible features, such as HTML5, CSS3, SVG support, and a new lightning fast JavaScript engine, Chakra! Further, they’re currently scoring a 55 on the Acid3 test – a figure that’s surely to increase substantially before the official release. What about the idea of Microsoft contributing to an open source project, jQuery, with their proposed templating engine? Within moments of these announcements, the Twitter-verse spilled “tears of joy.”

Want to dive in and check out the developer preview? That’s available too, starting today!




Take IE9 for a Test Drive.

Finally, we announced the availability of the first IE Platform Preview for developers, and our commitment to update it approximately every eight weeks. We want the developer community to have an earlier hands-on experience with the progress we’re making on the IE platform. The Platform Preview, and the feedback loop it is part of, marks a major change from previous IE releases.
IE Blog

Demos

Check out some of the demos below in each browser to learn the unique code required for each.


New JavaScript Engine: Chakra

JavaScript Graph

“You’ll notice that IE9 is faster at this benchmark than IE8 and several other browsers. It’s interesting to note that the difference between today’s IE9 preview and the browsers to its right in this graph. It takes about 70 seconds to identify a 300ms difference between browsers.”
IE Blog

Miscellaneous Tweets about IE9 from MIX 2010

“Video tag and SVG support in IE 9 as well – and it’s crazy fast. Very impressed.”
John Resig

“Microsoft to Expand its Collaboration with the jQuery Community”: http://bit.ly/cxybri
@jQuery

“Today makes me very happy to have come to work at Microsoft. Very excited right now to see the reactions of the community.”
Rey Bango

“They’re asking for help in getting ppl to move IE6 to IE8. They want users on modern browsers.”
Rey Bango

“Open source, open standards, open Microsoft. Today I woke up to a different world than I thought I was living in.”
Molly E. Holzschlag

“So what we have here is HTML5, CSS3, SVG 1.1 in IE9. If I weren’t seeing it with my own eyes, I wouldn’t freakin’ believe it.”
Molly E. Holzschlag

Check back for more details as they become available!



10 Features to Look Forward to in WordPress 3.0

10 Features to Look Forward to in WordPress 3.0

WordPress 3.0 is scheduled to be released within the next 30-60 days. There are some great new features coming, including custom post types, a new default theme, and a menu manager. Read on to find out what to expect in version three!

1. Choose your Username and Password

You’ll encounter new features as soon as you start! Currently, when you first install WordPress, you are assigned a default username of admin, and a randomly generated password. No more – now WordPress lets you choose a username and password when installing.

What does this mean for us?

This means that security within WordPress has been enhanced. Previously, a hacker could probably depend on the fact that there was a username called ‘admin’. This will no longer be the case in version three. Read any tutorial on securing WordPress – you will always be told to remove the admin username. You no longer need to!


2. New Default Theme!

WordPress 3.0 comes with a new default theme, called TwentyTen (2010, like the current year – go figure). Apparently, the WP team has an aim to release a new default theme every year! TwentyTen is a nice theme. The main typeface used is Georgia; it has two columns, with a widgetized sidebar and footer – and it even has some nice dropdown menus built in! Needless to say, custom header and background (new feature) functions are also available.

What does this mean for us?

We start off with a nice new theme, and bloggers have more options to try out before they start looking for themes. More options are always helpful, right?


3. Custom Background Support

WordPress 3.0 adds custom background support. Add the code below to your functions.php to make your theme support it:

add_custom_background();

Once that’s done, you’ll see an option called Background added under Appearance in the WordPress admin. This will allows you to upload a header image and customize it.

What does this mean for us?

This doesn’t really mean much to advanced theme developers, since they often provide an option like this themselves. Nevertheless, I have no doubt that the WordPress community will come up with some creative use for this.


4. Multi-site Capabilities and WPMU Codebase Merge

WordPress and WPMU (WordPress MultiUser) are merging their codebases. This makes it much easier to handle large WordPress networks. See the Multi-Site settings under Settings>Network.

What does this mean for us?

A lot! A network of WordPress sites is much easier to maintain – either with a subdomain.domain.com structure, or a domain.com/subdirectory structure. This network capability is optional, and WordPress and WPMU users shouldn’t face any difficulties while upgrading. Also, this makes it easier for WPMU users to utilize plugins – no more plugins that go bust or stop working.


5. Custom Post Types

A great new feature! Before, all you could add from the WordPress admin section was new posts and pages. Now, you can create new post types to show up. Add the following code to create a new post type called ‘Portfolio’:

function post_type_portfolio() {
	register_post_type( 'Portfolio',
                array( 'label' => __('Portfolio'), 'public' => true, 'show_ui' => true ) );
	register_taxonomy_for_object_type('post_tag', 'Portfolio');
}

add_action('init', 'post_type_portfolio');

What does this mean for us?

Quite simply, it means WordPress has become much more of a CMS(Content Management System). This holds unlimited possibilites for theme developers, and reduces the need to fiddle around with custom fields.


6. Custom Taxonomies

Custom taxonomies have been made easier to use, as well as hierarchical – which means you could have a taxonomy called ‘Rating’, with sub-taxonomies like PG-13, R , U etc.

What does this mean for us?
It means that WordPress is moving more and more from a blog-type CMS with effort required for better capabilities to a much more flexible and usable Content Management System.


7. Easy Menu Management

This is my favorite new feature in WordPress 3.0 – a menu manager. It’s developed by WooThemes’ WooNav, and I absolutely love it. You can create multiple menus, categories, and even custom external or internal links! The menu feature even comes with a default widget to add to any widget ready area – awesome, isn’t it?

What does this mean for us?

On the surface, this provides us a great UI (user interface) for adding new menus, it simplifies the job of WordPress theme developers and makes things as simple as possible for users. Benearth the surface, there is a lot more – this marks a point where commercial WordPress theme developers join hands with WordPress and contribute to it. A win-win situation for both, and an incentive to continue working.


8. A Bunch of Other Smaller Features

  • Welcome guide:Allegedly, WordPress 3.0 will be including a guide with it which helps users to know the system better and teach them basic usage.
  • Specific author templates: We already have hierarchy for categories and tags like category-{slug}.php followed by category-{id}.php in the Template Hierarchy, but now you can do the same for authors. So, if the author name was ‘Rohan’ with id 1, WordPress would first look for author-rohan.php, then author-1.php before author.php in the template files for display.
  • Media UI redeign: Started, but not implemented in WordPress 2.9, the Media tab in the admin panel may get a UI redesign

Conclusion

The screenshots and features that I’ve written about here are taken from the most recent nightly build. You may want to try it out yourself, though keep in mind that it’s still unstable. Nevertheless, WordPress is evolving at a rate no one could have predicted, and is fully morphing into a powerful and flexible CMS.



Win a Copy of Rockable’s Latest eBook, ‘How to Write Great Copy for the Web’

Win a Copy of Rockable’s Latest eBook, ‘How to Write Great Copy for the Web’

Today we’ve got three copies of the new eBook from Rockable and FreelanceSwitch, How to Write Great Copy for the Web, to give away. Entering takes seconds, just leave a comment below and three lucky people will be selected.

Win How to Write Great Copy for the Web

    How to Write Great Copy for the Web Cover
  • About the Book

    How to Write Great Copy for the Web is the latest book from Rockable Press. You may not know this, but Rockable is Envato’s book publishing house! This book takes a concise and practical approach to writing fantastic copy for any website.

    Ever been asked to write the copy for a website you’re working and had to say no because you aren’t a copywriter? Or maybe you did it for your client and weren’t happy with the final product? How to Write Great Copy for the Web will teach you how to add web copy writing to your skill set, maximizing your billable hours.

    This book will also help you write great copy for your portfolio or blog, to impress potential clients.

From the blurb: “In How to Write Great Copy for the Web, author Donna Spencer will help you start writing content for the web that works! Learn about how writing web copy differs from other forms of writing, and how writing useful, functional and concise copy can both help persuade your readers, and also help with search engine optimization!

Whether it’s for your own site, or for somebody else, How to Write Great Copy for the Web will quickly bring you up to speed with some clever strategies that will make you popular with your site’s visitors, or with your clients!”

How to Enter

For your chance to win one of the three books all you need to do is leave a comment below. Be sure to include your correct email address so that we can get in touch. The competition is open to anyone but you need to have entered by 12am March 18th AEST.

Want a Free Book? Join the Rockin’ List

Afraid you might not win? Sign up to the Rockin’ List to get the discount code for $5 off this great book and stay up to date with the latest Rockable news. You also get a free copy of Rockstar Personal Branding when you subscribe!



Learning Server-Side JavaScript with Node.js

Learning Server-Side JavaScript with Node.js

Node.js is all the buzz at the moment, and makes creating high performance, real-time web applications easy. It allows JavaScript to be used end to end, both on the server and on the client. This tutorial will walk you through the installation of Node and your first “Hello World” program, to building a scalable streaming Twitter server.

What is Node.js?

JavaScript has traditionally only run in the web browser, but recently there has been considerable interest in bringing it to the server side as well, thanks to the CommonJS project. Other server-side JavaScript environments include Jaxer and Narwhal. However, Node.js is a bit different from these solutions, because it is event-based rather than thread based. Web servers like Apache that are used to serve PHP and other CGI scripts are thread based because they spawn a system thread for every incoming request. While this is fine for many applications, the thread based model does not scale well with many long-lived connections like you would need in order to serve real-time applications like Friendfeed or Google Wave.

“Every I/O operation in Node.js is asynchronous…”

Node.js, uses an event loop instead of threads, and is able to scale to millions of concurrent connections. It takes advantage of the fact that servers spend most of their time waiting for I/O operations, like reading a file from a hard drive, accessing an external web service or waiting for a file to finish being uploaded, because these operations are much slower than in memory operations. Every I/O operation in Node.js is asynchronous, meaning that the server can continue to process incoming requests while the I/O operation is taking place. JavaScript is extremely well suited to event-based programming because it has anonymous functions and closures which make defining inline callbacks a cinch, and JavaScript developers already know how to program in this way. This event-based model makes Node.js very fast, and makes scaling real-time applications very easy.


Step 1 Installation

Node.js runs on Unix based systems, such as Mac OS X, Linux, and FreeBSD. Unfortunately, Windows is not yet supported, so if you are a Windows user, you can install it on Ubuntu Linux using Virtualbox. To do so, follow this tutorial. You will need to use the terminal to install and run Node.js.

  1. Download the latest release of Node.js from nodejs.org (the latest version at the time of this writing is 0.1.31) and unzip it.
  2. Open the terminal, and run the following commands.
    cd /path/to/nodejs
    make
    sudo make install
    		

    A lot of messages will be outputted to the terminal as Node.js is compiled and installed.


Step 2 Hello World!

Every new technology starts with a “Hello World!” tutorial, so we will create a simple HTTP server that serves up that message. First, however, you have to understand the Node.js module system. In Node, functionality is encapsulated in modules which must be loaded in order to be used. There are many modules listed in the Node.js documentation. You load these modules by using the require function like so:

var sys = require("sys");

This loads the sys module, which contains functions for dealing with system level tasks like printing output to the terminal. To use a function in a module, you call it on the variable that you stored the module in, in our case sys.

sys.puts("Hello World!");

Running these two lines is as simple as running the node command with the filename of the javascript file as an argument.

node test.js

This will output “Hello World!” to the command line when run.

To create an HTTP server, you must require the http module.

var sys = require("sys"),
    http = require("http");

http.createServer(function(request, response) {
    response.sendHeader(200, {"Content-Type": "text/html"});
    response.write("Hello World!");
    response.close();
}).listen(8080);

sys.puts("Server running at http://localhost:8080/");

This script imports the sys and http modules, and creates an HTTP server. The anonymous function that is passed into http.createServer will be called whenever a request comes in to the server. Once the server is created, it is told to listen on port 8080. When a request to the server comes in, we first send HTTP headers with the content type and status code of 200 (successful). Then we send “Hello World!” and close the connection. You might notice that we have to explicitly close the connection. This will make it very easy to stream data to the client without closing the connection. If you run this script and go to http://localhost:8080/ in your browser, you will see “Hello World!”


Step 3 A Simple Static File Server

OK, so we have built an HTTP server, but it doesn’t send anything except for “Hello World,” no matter what URL you go to. Any HTTP server must be able to send static files such as HTML files, images and other files. The following code does just that:

var sys = require("sys"),
    http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs");

http.createServer(function(request, response) {
    var uri = url.parse(request.url).pathname;
    var filename = path.join(process.cwd(), uri);
    path.exists(filename, function(exists) {
    	if(!exists) {
    		response.sendHeader(404, {"Content-Type": "text/plain"});
    		response.write("404 Not Found\n");
    		response.close();
    		return;
    	}

    	fs.readFile(filename, "binary", function(err, file) {
    		if(err) {
    			response.sendHeader(500, {"Content-Type": "text/plain"});
    			response.write(err + "\n");
    			response.close();
    			return;
    		}

    		response.sendHeader(200);
    		response.write(file, "binary");
    		response.close();
    	});
    });
}).listen(8080);

sys.puts("Server running at http://localhost:8080/");

We start by requiring all of the modules that we will need in our code. This includes the sys, http, url, path, and fs or filesystem modules. Next we create an HTTP server like we did before. This time, we will use the url module to parse the incoming URL of the request and find the pathname of the file being accessed. We find the actual filename on the server’s hard drive by using path.join, which joins process.cwd(), or the current working directory, with the path to the file being requested. Next, we check if the file exists, which is an asynchronous operation and thus requires a callback. If the file does not exist, a 404 Not Found message is sent to the user and the function returns. Otherwise, we read the file using the fs module using the “binary” encoding, and send the file to the user. If there is an error reading the file, we present the error message to the user, and close the connection. Because all of this is asynchronous, the server is able to serve other requests while reading the file from the disk no matter how large it is.

If you run this example, and navigate to http://localhost:8080/path/to/file, that file will be shown in your browser.


Step 4 A Real Time Tweet Streamer

Building on our static file server, we will build a server in Node.js that streams tweets to a client that is served through our static file server. To start, we will need one extra module in this example: the events module. Node has a concept called an EventEmitter, which is used all over to handle event listeners for asynchronous tasks. Much like in jQuery or another client side JavaScript framework where you bind event listeners to things like mouse clicks, and AJAX requests, Node allows you to bind event listeners to many things, some of which we have already used. These include every I/O operation, such as reading a file, writing a file, checking if a file exists, waiting for HTTP requests, etc. The EventEmitter abstracts the logic of binding, unbinding, and triggering such event listeners. We will be using an EventEmitter to notify listeners when new tweets are loaded. The first few lines of our tweet streamer imports all of the required modules, and defines a function for handling static files, which was taken from our previous example.

var sys = require("sys"),
    http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs"),
    events = require("events");

function load_static_file(uri, response) {
	var filename = path.join(process.cwd(), uri);
	path.exists(filename, function(exists) {
		if(!exists) {
			response.sendHeader(404, {"Content-Type": "text/plain"});
			response.write("404 Not Found\n");
			response.close();
			return;
		}

		fs.readFile(filename, "binary", function(err, file) {
			if(err) {
				response.sendHeader(500, {"Content-Type": "text/plain"});
				response.write(err + "\n");
				response.close();
				return;
			}

			response.sendHeader(200);
			response.write(file, "binary");
			response.close();
		});
	});
}

We have used the http module to create a server before, but it is also possible to create an HTTP client using the module. We will be creating an HTTP client to load tweets from Twitter’s public timeline, which is performed by the get_tweets function.

var twitter_client = http.createClient(80, "api.twitter.com");

var tweet_emitter = new events.EventEmitter();

function get_tweets() {
	var request = twitter_client.request("GET", "/1/statuses/public_timeline.json", {"host": "api.twitter.com"});

	request.addListener("response", function(response) {
		var body = "";
		response.addListener("data", function(data) {
			body += data;
		});

		response.addListener("end", function() {
			var tweets = JSON.parse(body);
			if(tweets.length > 0) {
				tweet_emitter.emit("tweets", tweets);
			}
		});
	});

	request.close();
}

setInterval(get_tweets, 5000);

First, we create an HTTP client on port 80 to api.twitter.com, and create a new EventEmitter. The get_tweets function creates an HTTP “GET” request to Twitter’s public timeline, and adds an event listener that will be triggered when Twitter’s servers respond. Because Node.js is asynchronous, the data in the body of the response comes in chunks, which are picked up by the response’s “data” listener. This listener simply appends the chunk to the body variable. Once all of the chunks have come in, the “end” listener is triggered, and we parse the incoming JSON data. If more than one tweet is returned, we emit the “tweets” event on our tweet_emitter, and pass in the array of new tweets. This will trigger all of the event listeners listening for the “tweets” event, and send the new tweets to each client. We retreive the new tweets every five seconds, by using setInterval.

Finally, we need to create the HTTP server to handle requests.

http.createServer(function(request, response) {
    var uri = url.parse(request.url).pathname;
    if(uri === "/stream") {

    	var listener = tweet_emitter.addListener("tweets", function(tweets) {
    		response.sendHeader(200, { "Content-Type" : "text/plain" });
    		response.write(JSON.stringify(tweets));
    		response.close();

    		clearTimeout(timeout);
    	});

    	var timeout = setTimeout(function() {
    		response.sendHeader(200, { "Content-Type" : "text/plain" });
    		response.write(JSON.stringify([]));
    		response.close();

    		tweet_emitter.removeListener(listener);
    	}, 10000);

    }
    else {
    	load_static_file(uri, response);
    }
}).listen(8080);

sys.puts("Server running at http://localhost:8080/");

Just as we did with our static file server, we create an HTTP server that listens on port 8080. We parse the requested URL, and if the URL is equal to "/stream", we will handle it, otherwise we pass the request off to our static file server. Streaming consists of creating a listener to listen for new tweets on our tweet_emitter, which will be triggered by our get_tweets function. We also create a timer to kill requests tht last over 10 seconds by sending them an empty array. When new tweets come in, we send the tweets as JSON data, and clear the timer. You will see how this works better after seeing the client side code, which is below. Save it as test.html in the same directory as the server side JavaScript.

<!DOCTYPE html>
<html>
	<head>
		<title>Tweet Streamer</title>
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
	</head>
	<body>
		<ul id="tweets"></ul>
		<script type="text/javascript">
		var tweet_list = $("#tweets");

		function load_tweets() {
			$.getJSON("/stream", function(tweets) {
				$.each(tweets, function() {
					$("<li>").html(this.text).prependTo(tweet_list);
				});
				load_tweets();
			});
		}

		setTimeout(load_tweets, 1000);
		</script>
	</body>
</html>

Here, we have a simple HTML page that imports the jQuery library and defines an unordered list to put the tweets in. Our client side JavaScript caches the tweet list, and runs the load_tweets function after one second. This gives the browser enough time to finish loading the page before we start the AJAX request to the server. The load_tweets function is very simple: It uses jQuery’s getJSON function to load /stream. When a response comes in, we loop through all of the tweets and prepend them to the tweet list. Then, we call load_tweets again. This effectively creates a loop that loads new tweets, which times out after ten seconds because of the timeout on the server. Whenever there are new tweets, they are pushed to the client which maintains a continuous connection to the server. This technique is called long-polling.

If you run the server using node and go to http://localhost:8080/test.html, you will see the Twitter public timeline stream into your browser.


Next Steps

Node.js is a very exciting technology that makes it easy to create high performance real time applications. I hope you can see its benefit, and can use it in some of your own applications. Because of Node’s great module system, it is easy to use prewritten code in your application, and there are many third party modules available for just about everything – including database connection layers, templating engines, mail clients, and even entire frameworks connecting all of these things together. You can see a complete list of modules on the Node.js wiki, and more Node tutorials can be found on How To Node. I would also recommend that you watch a video from JSConf, in which Ryan Dahl, the creator of Node, describes the design philosophy behind Node. That is available here.

I hope you have enjoyed this tutorial. If you have any comments, you can leave one here or send me a message on Twitter. Happy noding!



How to Build a Lava-Lamp Style Navigation Menu

How to Build a Lava-Lamp Style Navigation Menu

A couple weeks ago, I created a screencast that demonstrated how to build a three-level navigation menu. In a response email, one of our readers requested a tutorial on how to build a lava-lamp style menu. Luckily, it’s quite a simple task, especially when using a JavaScript library. We’ll build one from scratch today.

Screenshot

Prefer a Screencast?

Step 1 Create the Mark-up

Before we can create this neat functionality, we need a base from which to work from. In your favorite code editor, create an unordered list for your navigation, and import both jQuery and jQuery UI, via Google.

<!DOCTYPE html>

<html lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>SpasticNav  Plugin</title>
	<link rel="stylesheet" href="css/style.css" type="text/css" media="screen" />
</head>
<body>

<div id="container">

	<ul id="nav">
		<li id="selected"><a href="#">Home</a></li>
		<li><a href="#">About</a></li>
		<li><a href="#">Blog</a></li>
		<li><a href="#">More About My Portfolio</a></li>
		<li><a href="#">Contact</a></li>
	</ul>

</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>	

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>

</body>
</html>

Note how we gave an id of “selected” to the home page. This is fairly standard in most websites; it allows use to target the current page, and style that particular list item accordingly.

Next, we must decide how to best implement the lava-lamp functionality. To allow for reusability, we’ll package this little script into a plugin, and call it like:

$('#nav').spasticNav();

Since we’ve decided to build a plugin, let’s go ahead and create a new file for that script, and reference it in our mark-up. We’ll call it jquery.spasticNav.js.

<script type="text/javascript" src="js/jquery.spasticNav.js"></script>	

<script type="text/javascript">
$('#nav').spasticNav();
</script>
</body>

Step 2 Beginning the Plugin

To reduce the number of global variables that we must create, as well as remove any possibilities of the $ symbol clashing with other JavaScript libraries, let’s wrap our plugin in a self-executing anonymous function.

(function($) {

})(jQuery);

Now, jQuery will be passed into our plugin, and will be represented via the $ symbol.

Next, it’s generally a best practice to give the users of the plugin as much flexibility as possible. As such, we’ll give them the option of passing in an object-literal when they call the plugin to override a handful of settings. As I see it, they should be able to:

  • Set the amount of overlap for our little blob. This refers to how much the blob will exceed the height of the navigation menu.
  • Set the speed
  • Set a reset, which causes the blob to move back to the current page item (assuming that the user never clicks on a link)
  • Set the color of the blob. This can be accomplished with CSS, but it’s a nice convenience, nonetheless.
  • Set the easing option.

Now, we’ll name our plugin, and make it equal to a function. $.fn is simply an alias for jquery.prototype.

$.fn.spasticNav = function(options) {

};

Knowing that we’ll be allowing these overrides, we must make sure that we accept an “options” parameter.

Step 3 Configuration Options

Now that we’ve named our plugin, the next step is to create the configuration options.

options = $.extend({
	overlap : 20,
	speed : 500,
	reset : 1500,
	color : '#0b2b61',
	easing : 'easeOutExpo'
}, options);

Above, we’re taking the options variable, setting some default properties and values, and then extending it with whatever (if anything) the user passes in when they call the plugin. That way, the options they pass will override our default settings. For example, if, when I call this plugin, I pass:

$('#nav').spasticNav({
   speed : 2000,
   easing : 'easeOutElastic'
});

Those two properties will override the default settings, while the remainder of the options will remain the same.

Step 4 Implementing the Functionality

Now, we’re ready to cycle through each element that was passed to this plugin, and implement the lava-lamp functionality. Remember, we can’t assume that the user is going to pass a single element to this plugin. They could, if they wanted, reference a class, which refers to multiple items that should receive this functionality. As such, we’ll call this.each to iterate over each item in the wrapped set.

return this.each(function() {

});

Within this function, we’ll create some variables. Not all of them will immediately have values, but since the JavaScript engine will hoist all variable names to the top of the function anyways (behind the scenes), it’s generally a best practice to declare them at the top, and then initialize them later.

var nav = $(this),
	currentPageItem = $('#selected', nav),
	blob,
	reset;
  • nav : “Caches” this, wrapped in the jQuery object.
  • currentPageItem : Contains the list item with an id of selected. We pass a second parameter to set the context to search from. That way, we don’t have to traverse the entire dom to find this element.
  • blob : For lack of a better word, this variable will reference the highlighter, that will follow our mouse when we hover over the menu.
  • reset : This will store a reference to the setTimeout function that will create later. It’s needed in order to call clearTimeout. More on this soon…

Now that we’ve declared/initialized our variables, let’s create the actual blob, so to speak.

$('<li id="blob"></li>').css({
	width : currentPageItem.outerWidth(),
	height : currentPageItem.outerHeight() + options.overlap,
	left : currentPageItem.position().left,
	top : currentPageItem.position().top - options.overlap / 2,
	backgroundColor : options.color
}).appendTo(this);

The reason why we’re calling the CSS method, rather than simply adding a class, is because these values will vary depending on the current page’s list item. As such, we must use JavaScript to retrieve they values.

  • width: Get the width of currentPageItem, including any borders and padding.
  • height: Get the height of currentPageItem, including any borders and padding. Also, add the amount of overlap, to make the blob extend outside of the menu.
  • left: Sets the left property of the blob equal to the left position of the currentPageItem. (We must set a positioning context in our CSS for this value to take effect.)
  • top: Sets the top value as well, and vertically centers the blob.
  • backgroundColor: Sets the background color.

Finally, we append this new list item to this, or #nav.

Next, we need to store a reference to #blob. That way, we don’t have to search the DOM everytime we wish to access it. We declared the blob variable at the top of the function. Now, let’s initialize it.

blob = $('#blob', nav);

Step 5 The Hover Event

We must now “listen” for when the user hovers over one of the list items (excluding the blob of course) in our navigation menu. When they do, we’ll set the width and left properties of the blob equal to that of the currently hovered list item.

$('li:not(#blob)', nav).hover(function() {
	// mouse over
	clearTimeout(reset);
	blob.animate(
		{
			left : $(this).position().left,
			width : $(this).width()
		},
		{
			duration : options.speed,
			easing : options.easing,
			queue : false
		}
	);
}, function() {
	// mouse out
	reset = setTimeout(function() {
		blob.animate({
			width : currentPageItem.outerWidth(),
			left : currentPageItem.position().left
		}, options.speed)
	}, options.reset);

});

To summarize the script above…

  • Get all list items – not the #blob – within the navigation menu, and when they’re hovered over, run a function.
  • Animate the blob, and set its left and width values equal to that of the hovered list item.
  • Pass an object literal as the second parameter of animate, and set the duration and easing equal to what we set in our configuration options. Set queue to false to prevent animation build-up.
  • When they mouse out, call setTimeOut, which will push the blob back to the current page item. If we didn’t do this, and the user didn’t click on a navigation link, the menu would show that they were on
    a different page entirely. This will, after a second or so, animate the blob back to currentPageItem.

And that’s all there is to it! This is a super simple plugin. The next step is to style our navigation menu.

Step 6 Styling the Menu

Without any styling, our menu should look similar to this:

Unstyled mark-up

Let’s first style the “nav” ul. Open your style.css file, and add:

#nav {
	position: relative;
	background: #292929;
	float: left;
}
Styling the navigation menu

Next, we’ll style each list item.

#nav li {
	float: left;
	list-style: none;
	border-right: 1px solid #4a4a4a;
	border-left: 1px solid black;
}

This simply floats each list item to the left, and adds a border to each side.

Styling the list items

Moving along, we next must style the anchor tags within our navigation menu.

#nav li a {
	color: #e3e3e3;
	position: relative;
	z-index: 2;
	float: left;
	font-size: 30px;
	font-family: helvetica, arial, sans-serif;
	text-decoration: none;
	padding: 30px 45px;
}

We’re setting a color, floating them to the left, setting some font values, and a healthy amount of padding. Take note of the z-index property. This is a necessity, and will be explained shortly. However, remember that, in order to adjust the z-index, we must set a positioning context, which we’ve done.

Styling the anchor tags

Because we’re not implementing a full reset stylesheet, let’s ensure that we zero out any default margins and padding on our ul and li, just to save any potential headaches.

ul, li {
	margin: 0; padding: 0;
}

The last step is to style the blob itself!

#blob {
	border-right: 1px solid #0059ec;
	border-left: 1px solid #0059ec;
	position: absolute;
	top: 0;
	z-index : 1;
	background: #0b2b61;
	background: -moz-linear-gradient(top, #0b2b61, #1153c0);
	background: -webkit-gradient(linear, left top, left bottom, from(#0b2b61), to(#1153c0));
	-moz-border-radius: 4px;
	-webkit-border-radius: 4px;
	-moz-box-shadow: 2px 3px 10px #011331;
	-webkit-box-shadow: 2px 3px 10px #011331;
}

Once again, we set some pretty colors for our borders, and add some background colors (including CSS3 gradients/borders/shadows for Firefox and Safari/Chrome). Once again, we see that z-index property. Without this, the blob will display above all of the text in the navigation menu. To counter this, we must be sure that its z-index property is LOWER than the list item’s! We also must set the position to absolute in order to adjust its top and left values with our plugin.

Screenshot

Conclusion

That’s all there is to it! With minimal effort, we’ve created a really neat looking navigation menu from scratch. Let me know if you have any questions! Thanks for reading and watching.



Quick Tip: HTML5 Video with a Fallback to Flash

Quick Tip: HTML5 Video with a Fallback to Flash

In this video quick tip, we’ll review how to work with HTML 5 video in your own projects. Because older browsers and Internet Explorer do not understand the <video> element, we must also find a way to serve a Flash file to viewers who are utilizing those browsers.

Unfortunately, much like HTML 5 audio, Firefox and Safari/Chrome don’t quite agree when it comes to the file format for videos. As such, if you wish to take advantage of HTML 5 video at this time, you’ll need to create three versions of your video.

  • .OGG: This will make Firefox happy. You can use VLC (File -> Streaming/Export Wizard) to convert your video to this format easily.
  • .MP4: Many screencasting tools automatically export to Mp4; so you can use that file for Safari and Chrome.
  • .FLV/.SWF: Not all browsers support HTML 5 video, of course. To compensate, make sure that you add a fallback Flash version as well.
<!DOCTYPE html>

<html lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>untitled</title>
</head>
<body>
<video controls width="500">
	<!-- if Firefox -->
	<source src="video.ogg" type="video/ogg" />
	<!-- if Safari/Chrome-->
	<source src="video.mp4" type="video/mp4" />
	<!-- If the browser doesn't understand the <video> element, then reference a Flash file. You could also write something like "Use a Better Browser!" if you're feeling nasty. (Better to use a Flash file though.) -->
	<embed src="http://blip.tv/play/gcMVgcmBAgA%2Em4v" type="application/x-shockwave-flash" width="1024" height="798" allowscriptaccess="always" allowfullscreen="true"></embed>
</video>
</body>
</html>

There are a handful of attributes available to the <video> element.

  • Controls: Display the play/stop buttons?
  • Poster: The value can be a path to an image, that will serve as the display of the video before it is played.
  • AutoPlay: Immediately play the video when the page is loaded?
  • Width: The desired width of the video. By default, the browser will automatically detect the dimensions of the supplied video.
  • Height: The desired height of the video.
  • Src: The path to the video file. It’s better to use the <source> child element instead for this task.

Dos and Don’ts of HTML 5 Video

  1. DO create three version of your video to make Firefox, Safari/Chrome, and IE happy. (.ogg, .mp4, .flv/.swf)
  2. DO NOT omit one of these formats. Unfortunately, you can’t easily choose to serve HTML 5 video to Firefox, and the Flash fallback to Safari. Safari understands the <video> element, and will expect to find a suitable video format to load. If one is not found, it will display an empty player.
  3. DO keep in mind that full-screen support will not work in Safari and Chrome. However, with the release of Firefox 3.6, you can right-click, and view in full screen.
  4. DO remember that the reason why IE loads the Flash file instead is because it does not understand what the <video> element is. However, if a browser DOES understand that element, it will expect to find a suitable file to load.

Please note that, if I can find a suitable work-around for the full-screen problem, we’ll be using this method on Nettuts+ in the near future!



CodeIgniter from Scratch: File Operations

CodeIgniter from Scratch: File Operations

In today’s episode, we are going to be working with several helper functions, related to files, directories, and downloads. We are going to learn how to read, write, download files, and retrieve information about both files and directories. Also at the end we will build a small file browser that utilizes jQuery as well.

Catch Up

Day 11: File Operations

Get the Flash Player to see this player.

Final Example



New Premium Series: Tumblr Theme Design – Start to Finish

New Premium Series: Tumblr Theme Design – Start to Finish

Tumblr’s popularity over the last year has increased exponentially. The reason why is quite simple: Tumblr is flexible, powerful, and, most importantly, a pleasure to work with. Unfortunately, there aren’t many training resources available for the platform yet. In this video series, we’ll go through the process of taking a Tumblr theme, designed in Photoshop, and converting it into a fully working theme – in just a few hours.

To take advantage of this mammoth video series, become a Premium member!

Watch the Intro

Get the Flash Player to see this player.

The Full Series

  • Chapter 1: Intro
  • Chapter 2: Slicing the Design
  • Chapter 3: Creating the Markup and Adding the Tumblr Template Tags
  • Chapter 4: Adding the CSS
  • Chapter 5: Configuration Options
  • Chapter 6: @Font-Face and Custom Fonts
  • Chapter 7: Slide-out Panel – HTML and CSS
  • Chapter 8: Slide-out Panel – jQuery

Final Design

Thanks to Kate Payton for submitting the design for this tutorial.

Join Net Premium

NETTUTS+ Screencasts and Bonus Tutorials

For those unfamiliar, the family of TUTS sites runs a premium membership service. For $9 per month, you gain access to exclusive premium tutorials, screencasts, and freebies from Nettuts+, Psdtuts+, Aetuts+, Audiotuts+, and Vectortuts+! For the price of a pizza, you’ll learn from some of the best minds in the business. If you’re curious about the other Premium tutorials that we have available, check here. Join today!



Inspiration: Awesome Book-Related Website Designs

Inspiration: Awesome Book-Related Website Designs

If you’re a book lover, you may have noticed that the vast majority of book-related websites out there leave a bit to be desired when it comes to design and information architecture. In fact, some author and publisher websites make me feel like my eyes might bleed!

But there are some gems out there, and we’ve collected some of the best. If you know of any other fantastic book-related websites, whether they’re for authors, individual books, publishing companies, or blogs, let us know in the comments.

Authors & Individual Book Sites

Author websites are some of the more challenging sites to design. If an author has a large backlist, it can be difficult to figure out how to showcase all of their work effectively. And if the author has only published one or two books, it can be hard to have an effective site that doesn’t feel empty.

And in reality, there are a lot of things an author’s site needs to accomplish. It needs to provide readers and potential readers with information about the books and why they might be interested in reading them. It needs to give booksellers information about the books, and why they should stock them. And it needs to act as a constant promotional tool that will help the author sell more books and gain more fans.

Dear Author has a great post on what many author websites are lacking. The list includes things like a printable book list, a link on the home page to contact the author, and a highly visible “coming soon” section. Check out the full list for more points to keep in mind if you’re designing an author’s website.

Here are a few great author and book websites you should be sure to check out for inspiration and ideas.

No One Belongs Here More Than You

This is one of the most creative books websites I’ve ever seen. While it’s not the most user-friendly of sites, it suits its purpose and does well to hold reader interest.

Justine Larbalestier

An excellent, clean-looking design that still has plenty of character. Her books are prominently displayed on the home page, along with links to her blog, about information, and other important parts. She also includes information about events, interviews, and specific book info on the home page, a big plus for readers and book sellers.

Stephen King

Stephen King’s presents its own challenges to a designer, mainly the sheer volume of information it needs to contain. King has written well over sixty books, has had a number of his books adapted for the screen, and has written numerous short stories. But his site manages to include all the pertinent information a visitor might be looking for while also showcasing his best and most recent works, all while maintaining a very streamlined and professional design.

Cherry Adair

Cherry Adair’s website fits well with the types of books she writes. The only downside to the site is that it’s entirely Flash-based, though the interface itself is slick and very responsive. She includes all of the information one would expect on an author site, including a printable, PDF booklist.

Jim Collins

Jim Collins’ site takes a much more minimalist design approach than many of the others on this list. The color scheme is limited and sophisticated, there’s plenty of white space, and only necessary content is included.

Jean Chatzky

Jean Chatzky’s website is well-suited to the types of books she writes and the brand she’s built for herself (you may recognize her from her regular appearances on the Today Show). It’s professional but unintimidating and has a friendly feel to it. It also provides all the necessary information you’d expect and is easy to navigate.

Hank Phillippi Ryan

Hank Phillippi Ryan’s website is bright and colorful, which matches the covers and style of her books. The layout is reminiscent of a grid layout and makes good use of negative space.

Caroline Tiger

Caroline Tiger’s site has some of the best use of color of any author site I’ve seen. Navigation is simple and straightforward, the emphasis is placed squarely on her books, and the overall impression is professional but relaxed.

Nicholas Sparks

Nicholas Sparks’ website makes great use of large background images and transparency. It’s easy to find the information you might be looking for, with prominent links to his books and movies, as well as appearances and biography information.

Publishers

Publisher websites have to be many things to many people; not always an easy task to do well. They have to showcase their books to potential readers. They have to appeal to booksellers and convince them to stock more of their books. They have to give information to prospective authors, either in the form of submission guidelines or guidelines that tell them they don’t accept unagented submissions. They have to provide information to the media and book reviewers. And sometimes, in the case of the larger publishing conglomerates, they also have to present a united front across multipe imprints.

The best publisher sites showcase recent books as well as best sellers. They make it easy for readers and booksellers to make decisions regarding book purchases. And they provide all the necessary information about the company, the books, and the authors for anyone looking.

Here are some of the best book publisher websites out there. They run the gamut from small publishers with only a handful of books to large publishing houses that publish hundreds of titles each year. What they all have in common is good information architecture, a clean style, and excellent user experience.

Dragon International Independent Arts

The DIIArts site packs a lot of information into a small space while maintaining an uncluttered and clean-looking layout. Their main nav includes nine tabs while still leaving some breathing room. The use of icons throughout the site helps to unify everything, as does the light color scheme.

Arcadia Publishing

Arcadia Publishing’s site fits its business perfectly. It has a vintage feel to it, which fits them since they’re publishers of historical nonfiction. The site is easy to navigate and effectively showcases important information (like the fact that they offer free shipping).

Melville House Publishing

The Melville House Publishing website has a simple blue and white theme throughout. It has a minimalist, grid-based layout nad a lot of white space. Information is easy to find and their books are displayed prominently.

Princeton Architectural Press

Princeton Architectural Press’s website is great because it’s design is a bit unexpected. The bright yellow background and grid-based layout are visually striking, which is entirely appropriate for a publishign company that focuses so heavily on design, but also a bit unexpected for a site in such a conservative industry.

Penguin Group USA

Among all of the big-name publishers out there, Penguin has one of the most attractive websites. Their layout is well-ordered, the color palette is refined, and they place emphasis where appropriate. There’s a ton of information on the site, and yet it feels uncluttered.

Timber Press

The Timber Press website makes great use of color and has a fantastic layout. The design is eye-catching and easy to navigate, with a well-implemented slideshow showcasing some of their books on the home page.

Llewellyn

Llewellyn’s website uses a muted color palette and three column layout that creates a sophisticated and professional feel to their site. They make it easy to browse their books, as well as to find other information about the company and their authors.

Storey Publishing

Storey Publishing is another company that opted for a muted color palette and simple layout. The green accents on the site fit well with the country-living and outdoor-themed books they publish, as do the graphics throughout the site.

Gibbs Smith

Gibbs Smith makes great use of Flash to showcase books on their home page, but otherwise keeps their layout fairly simple. They emphasize their best-sellers but make it easy to browse their entire catalog or find information about their authors. The red, burgundy and gray color scheme is sophisticated and feels very neutral.

Other Sites

Publisher and author websites aren’t the only sites out there that target book lovers. There are communities for readers (and writers), blogs and book review sites, and service sites for readers and writers alike.

The sites below target many different demographics, but each focuses on great user experience and simple architecture. Each has its own distinct style that adds to the user’s overall impression of the site and the company or people behind it. And each one has a clear purpose and mission that they accomplish well.

IndieBound

IndieBound is a community for independent bookstores and their customers. Their site is well-laid-out, has a great color scheme, and a unique design. They have a lot of information on the site, but it remains easy to navigate and find the information you need. They even manage to make the wide variety of graphics used on the site appear cohesive.

The Fiction Project

The Fiction Project at Art House Co-Op has a really awesome site design. The overall look represents the artistic sensibility of the project, but all information about the project is easily found and legible.

Lulu

Self-publishing company Lulu has a well-designed website that focuses on user experience. They keep graphics simple and use them specifically to highlight their services. The color scheme is consistent (white, blue and orange), and there’s plenty of negative space in the design. What sets Lulu’s site apart from many other self-publishing sites is that they’ve made it just as easy for book buyers to use the site as they have for authors.

Readerville

Readerville uses a simple two-column design with brownish-orange, burgundy, and muted blue accent colors. Readability is given the utmost importance in this design, with usability a very close second. While the site is no longer updated, it is still a great example of a book-related site design.

DailyLit

DailyLit, a service that delivers daily reading to your email inbox, has a fantastic website that uses a muted, cool color palette and grid-based layout. The site is easily navigated and showcases their services and the books available.

Blurb

Blurb is another self-publishing service that puts more emphasis on style than many other self-publishing sites. They offer good user experience for both authors and book buyers, and showcase “staff picks” on the home page (something many self-publishing companies don’t bother with).

The Millions

The Millions is a book review and culture site that uses a grid layout and mostly-black and white color scheme with bright orange accents. The layout of the site is fantastic, and the entire thing feels very modern and refreshing.

Guys Read

Guys Read is a literacy site for boys that places a heavy emphasis on typography. The site uses a red-white-and-blue color scheme and plenty of white space. It uses a mostly two-column layout and has a very masculine feel to it without feeling stuffy or staid.



Quick Tip: The Difference Between Live() and Delegate()

Quick Tip: The Difference Between Live() and Delegate()

In jQuery 1.3, the team introduced the live() method, which allows us to bind event handlers to elements on the page, as well as any that might be created in the future dynamically. Though not perfect, it definitely proved to be helpful. Most notably, live() bubbles all the way up, and attaches the handler to the document. It also ceases to work well when chaining method calls, unfortunately. Delegate() was introduced in version 1.4, which almost does the same thing, but more efficiently.

We’ll examine the specific differences between the two methods in today’s video quick tip. Thanks to the FireQuery Firebug extension, we’ll have the tools to more easily understand how each method functions.

<ul id="items">
	<li> Click Me </li>
</ul>
// Bind attaches an event handler only to the elements
// that match a particular selector. This, expectedly,
// excludes any dynamically generated elements.
$("#items li").click(function() {
	$(this).parent().append("<li>New Element</li>");
});

// Live(), introduced in 1.3, allows for the binding
// of event handlers to all elements that match a
// selector, including those created in the future.
// It does this by attaching the handler to the document.
// Unfortunately, it does not work well with chaining.
// Don't expect to chain live() after calls like
// children().next()...etc.
$("li").live("click", function() {
	$(this).parent().append("<li>New Element</li>");
});	

// Delegate, new to version 1.4, perhaps should have been a complete
// replacement for Live(). However, that obviously
// would have broken a lot of code! Nonetheless,
// delegate remedies many of the short-comings
// found in live(). It attaches the event handler
// directly to the context, rather than the document.
// It also doesn't suffer from the chaining issues
// that live does. There are many performance benefits
// to using this method over live().
$('#items').delegate('li', 'click', function() {
	$(this).parent().append('<li>New Element</li>');
});	

// By passing a DOM element as the context of our selector, we can make
// Live() behave (almost) the same way that delegate()
// does. It attaches the handler to the context, not
// the document - which is the default context.
// The code below is equivalent to the delegate() version
// shown above.
$("li", $("#items")[0]).live("click", function() {
	$(this).parent().append("<li>New Element</li>");
});

Conclusion

This can definitely be a confusing topic. Please feel free to ask questions, or discuss within the comments. Thanks so much to Elijah Manor for clarifying a few things for me on this topic!