Build an early sign-up mailing list system

Note: This article has been marked for a quality review and will soon be updated.

When you've got a great idea for a product its often hard to resist buying up the domain name for it, but what do you put there? A coming soon logo? A paragraph about what you're making? How about allowing visitors to sign-up to hear updates when the products becomes public? The last point is the most useful because not only does it let you keep track of early interest, it ensures your visitors don't go getting all excited and then forget about the product when it launches a couple of months down the line. So our system will allow users to pop their email address into a form, and will then insert it into a database and send an email to the new subscriber. We'll look at how to build in admin notification, as well as having a system in place that requires users to confirm their email address before they are added to the list. We'll be making a script that we can use on multiple sites with little alteration so if, like me, you have a number of projects awaiting public release you will be able to stick it on all your different servers with relative ease. Let's get started.

First up we will do the simple task of creating our database. Depending on the features you want, you may want to alter the structure a little, but in our case we will build in support for users to enter their name, email, and to have to confirm their subscription. So for that we will need the fields: ID - our primary key, name - if we want to collect the subscriber's name, email, confirmed - if they have verified their email address, site - which mailing list they subscribed to, created - when did they subscribe? So our process should look like this: User Enters Email -> Added to Database & Verification Email Sent -> User Confirms -> Database Updated. So go ahead and add that table to your database, I called my database 'mailing_lists', with my table named 'users'. Here is the SQL to create the table:

CREATE TABLE `users1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(150) NOT NULL,
  `email` varchar(200) NOT NULL,
  `confirmed` tinyint(4) NOT NULL DEFAULT '0',
  `site` varchar(150) NOT NULL,
  `created` varchar(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

Now we'll build the main PHP script list.php that will handle all the heavy lifting. To begin we'll define some important variables, and create a connection to our database, here's what that looks like:

define(REQUIRES_NAME, false);
define(NOTIFY_OWNER, true);
define(OWNER_EMAIL, 'YOUR EMAIL HERE');
define(SITE_NAME, 'SITE NAME HERE');

define(DB_USER, "USERNAME");
define(DB_PASS, "PASSWORD");
define(DB_HOST, "DB HOST");
define(DB_NAME, "DB NAME");

$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

We're using MySQLi for a speed increase and to allow us to use Object Orientated Programming. Now we will create the function that will allow us to insert new subscribers to the database, we'll call it addToList().

function addToList($email, $name = ''){
	if($name=='' && REQUIRES_NAME){
		// Name required and not provided
		echo 'Invalid name';
	}else {
		$email = strtolower($email);
		global $db;
		
		$cur = $db->query("SELECT * FROM users WHERE email = '".$email."' && site = '".SITE_NAME."'");

		if($cur->num_rows > 0){
			echo 'Duplicate entry detected';
			return false;
		}else {
			$db->query("INSERT INTO users(name, email, confirmed, site, created) VALUES('$name', '$email', 0,'".SITE_NAME."', '".time()."')") or die('Error inserting into database');
			return true;
		}		
	}
}

Let's see what that function does. First up we check if we should be collecting the user's name, if we are and it isn't there, we stop the script and send out a warning. Otherwise we set up the $email variable and make sure we have access to our $db variable. The next part makes queries the database to make sure the user hasn't already subscribed to the list, if they have we tell them that a duplicate entry was detected, and if not we insert their data into our table. Great stuff, we've done the main part of our script. But if we want the user to be able to confirm their email address, and even send an email to the admin, we'll need to write a few more functions. And to make sure we don't go writing duplicate code, we will create our own function for sending mail that will in turn call PHP's mail() function. Here's what it looks like:

function list_mail($to, $subject, $message){
	if(!empty($to) && !empty($subject) && !empty($message)){
		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";	
		$headers .= 'From: noreply@'. SITE_NAME . "\r\n";		

		mail($to, $subject, $message, $headers);
	}else {
		echo 'Bad parameters passed to list_mail()';
	}
}

It's a pretty basic function that checks that the parameters of $to, $subject, and $message aren't empty, and then sends a HTML email if everything checks out. Otherwise we echo out a handy error.

The next two functions we will write are the two that handle the content of the emails sent to our users and our admin, so you'll need to alter them accordingly.

function sendConfrimMail($email, $name = ''){
	$subject = 'Subscription Confirmation';
	$message = '<html>
			<head><title>Subscription Confirmation</title></head>
			<body>
				<center><p style="margin-top:20px;">You have successfully subscribed to updates from '.SITE_NAME.', thank you for signing up to be the first to receive information about our exciting new project, we look forward to providing you with something amazing in the near future.

<p>But before you can receive updates you need to confirm your subscription by visiting: http://'.SITE_NAME.'/confirm.php?e='.$email.'&t='.md5($email.SITE_NAME).'</p> <p>-The Management</p></center> </body> </html>'; list_mail($email, $subject, $message); } function notifyOwner(){ global $db; $subCount = $db->query("SELECT COUNT(*) FROM users WHERE site = '".SITE_NAME."'"); $subCount = $subCount->fetch_array(); $subCount = $subCount[0]; $subject = 'New '.SITE_NAME.' Subscription!'; $message = '<html> <head><title>New '.SITE_NAME.' Subscription!</title></head> <body> <center><p style="margin-top:20px;">A new subscription has just been submitted to the site! We currently have '.$subCount.' subscribers!</p> <p>Let\'s make em happy!</p></center> </body> </html>'; list_mail(OWNER_EMAIL, $subject, $message); }

Now those functions both do essentially the same thing, they just send messages to different people. And as a handy addition the notifyOwner() function also includes the subscriber count in the message. Feel free to go made coding up a beautiful HTML email and playing around with the content at this point.

You should notice that in the confirmation email we included a link that links to the site name we provided /confirm.php, and passes the variables 'e' and 't' (not the friendly alien) along with it. The 't' variable is the encrypted version of the user's email, plus our site name as a salt. This is something we can easily replicate when we build confirm.php a little later.

So where are we at? Well we have a bunch of great functions that we can port to different sites with relatively little hassle, but, as the more astute among you may have noticed, none of them are ever called! So we're going to have to write 10 more lines of code to make it happen! And it just so happens I've already done that :).

if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
	if(addToList($_POST['email'], $_POST['name'])){
		sendConfrimMail($_POST['email'], $_POST['name']);
		if(NOTIFY_OWNER){
			notifyOwner();
		}
		echo 'Success';
	}
}else {
	echo 'Invalid email address';
}

So this code first validates the email address passed to us using the filter_var() function that works it's magic by using a complex regular expression for validation - this saves us having to write one ourselves. Next we call our addToList() function from within an if statement. This ensures that the following code only executes if all goes well, and because the function also handles the error output we don't need a matching else for that statement. If all does go well, we then send the confirmation email to our user, check if we need to notify the list's owner/admin, and then echo 'Success'. Otherwise we tell the world that the email provided wasn't valid. Excellent. Now we only have 2 more parts to add; that's the form itself, with which we will use some jQuery to handle our error, and the confirmation page. So let's start with the server-side.

Here is the code for confirm.php:

if(!empty($_GET['e']) && !empty($_GET['t'])){
	define(SITE_NAME, 'SITE NAME');
	
	define(DB_USER, "USERNAME");
	define(DB_PASS, "PASSWORD");
	define(DB_HOST, "DB HOST");
	define(DB_NAME, "DB NAME");
	
	$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

	$email = $db->real_escape_string($_GET['e']);

	$result = $db->query("SELECT * FROM users WHERE email = '$email' AND site = '".SITE_NAME."'");
	
	if($row = $result->num_rows > 0){
		if($row['confirmed']=='0'){
			if($_GET['t']==md5($_GET['e'].SITE_NAME)){
				$db->query("UPDATE users SET confirmed = 1 WHERE email = '$email' AND site = '".SITE_NAME."'");
				echo 'Subscription confirmed!';
			}else {
				echo 'Invalid Token!';
			}
		}else {
			echo 'Email already confirmed!';
		}
	}else {
		echo 'No record found.';
	}

}else {
	echo 'Invalid URL!';
}

So here we check to make sure we have both the user's email, and their confirmation token, and then connect to our database. We then create a variable called $email - a sanitised version of the email addressed passed to us in the URL. However we still use the one provided to us later - this is because a user might have a special character in their email address, and may not be a hacker, so if our function returns something slightly different it will alter the confirmation token. We then make sure that the record exists, and that it hasn't yet been confirmed. If it hasn't we test the confirmation token and update the database. Notice the 5 echo statements to keep the user updated about what's going on. And that's it for PHP for today. Let's build our snazzy form.

Now our script expects only the email address of any subscriber, but we can optionally also pass it the name of a new subscriber. In this case we'll just pass the email address to keep it simple, but if you wanted to include the name you would add another input named 'name'.

<form action="list.php" method="post">
	<span class="status">Enter your email address below to hear updates.
<input type="text" name="email" placeholder="Email address..." /> <input type="submit" value="Subscribe to Updates" /> </form>

And we'll add some jQuery to submit the form using AJAX, and to handle the errors accordingly.

$(function(){ 
	$('form').submit(function(){
		$.ajax({
			url: 'list.php',
			type: 'POST',
			data: 'email='+$('input[name=email]').val(), //Add name here if you want it
			success: function(data){
				if(data=='Success'){
					$('form input').fadeOut(500, function(){
						$('.status').text('Email submitted! Please check your email to confirm your subscription.').css('font-weight','bold');
					});
				}else if(data=='Invalid email address') {
					$('.status').text('Please ensure you have entered a valid email address!').css('font-weight','bold');
				}else if(data=='Duplicate entry detected'){
					$('.status').text('Duplicate entry detected! You have already signed up.').css('font-weight','bold');
				}else {
					$('.status').text('Error processing data, please try again in a moment.').css('font-weight','bold');
				}
			}
		});
		return false;
	});
});

The code above is some simple jQuery to submit the form to list.php, and to handle what it returns. If the script outputs 'Success' it's all good, and we can tell the user just that. We then process the rest of the errors that we cater for in our script, and humanise the data accordingly, and if the error is anything else - possibly to do with the server being busy, we just put out a standard error message.

And that is how to build an early sign up mailing list!

Download the source here.

An introduction to OOP

Note: This article has been marked for a quality review and will soon be updated.

Object-orientated programming is a concept that is more likely to pop up when programming desktop applications rather than those for the web. But once you start using OOP you will wonder why you ever used procedural programming (that's simply using a program that calls a load of functions/procedures), well maybe not completely - OOP has its place on the web, and in this tutorial we will explore a practical usage of the common programming-paradigm. So what is it? Put simply OOP is when programmers create objects in which they can store data, and ask those objects to do certain things. So for an example, we might have a person object for which we can set things like eye colour and height - these values would be stored in variables. We might also have some instructions that we can give to our person object* like "star jump!", our person would then do a star jump, in our case it might be more like writing something to the screen like "I just did a star jump!".

So how do we know what variables and instructions we have for any give object? Put simply, with our class. A class is a file which contains all the information about any objects that will be created. The most common analogy for a class is a blue-print - it's a good one, because our class contains all the information we need to know about anything we make using it. Just as a blueprint for a house tells us the dimensions of the thing, it also shows us how the doors open and where the water comes in. When we actually make our house in the real world we build it, in the world of computers we instantiate it. When we've finished building in the real world we say we have a house, in programming we call it an instance of the house class.

Deep breaths people! Let's move onto the why we might want to program like this.

OOP really re-enforces a number of good programming techniques, and the 4 principles of the paradigm are as follows: A PIE. No, not the tasty treat, but another acronym! Now if your background isn't in programming the next 4 words might fly over your head - but for the moment I need you to grab a net and get ready to catch them. A PIE stands for Abstraction, Polymorphism, Inheritance, and Encapsulation. Now if you've done any programming on the web or otherwise it's likely you've done at least 2 of the above things. So let's go through them one at a time.

Abstraction

This refers to the technique of taking a problem and focusing on the 'abstract' rather than the individual. Take a look at this function:

function addMyNumbers($a, $b){
    return $a + $b;
}

Above is a very basic example of abstraction at work. Instead of writing 4 + 7 directly into our code, we have written a function that adapts to return a value based on what we pass to it. Therefore we have abstracted that concept. In OOP we use abstraction to make classes. For instance, in our person class we might have an instance method of runOneMileThatWay() - a method that does exactly what the name suggests. But the problem with such a method is that it is very specific. If we wanted our person object to run 5 miles instead of 1 (they are very fit by the way), we would either have to write a new method, or call the same method 5 times. The solution to this is to copy our add method above, and pass a value which tells our instance to run $x amount of times. This makes our program more efficient and easier to maintain.

Polymorphism

If any of these words is going to trip you up, this is gonna be the one. Bear with me here. Polymorphism is the term used to describe the idea that variables, objects, and functions can have more than one form. We don't need to go too deep into why this is important, but let's take a look at an example where polymorphism comes into play.

$x = (int) 4;
$y = (float) 5.76532;

echo $x + $y;

Perfectly legal right? We've declared 2 variables - one integer, and one floating point number, and then added them together. Run this code and you get a number just below 10. But technically this shouldn't work. Integers and floats are stored using different methods, but thanks to polymorphism PHP knew to simply add the two together as we humans would, instead of complaining about the distinction between integers and floats. And that's all you really need to know about polymorphism for now.

Inheritance

Nice and simple - your mum has blue eyes, so you have blue eyes right? Well human genetics is a little more complex than what we're going to be doing, but you get the idea - you inherit (or get) your traits from your parents and general ancestry. In OOP our objects can also inherit things like methods from their super classes. In certain languages you must always tell the world (or rather compiler) what class you are inheriting from. For example in Objective-C - the language used on iOS, the most common class to inherit from is called NSObject. As I said before you can inherit methods which ensures you don't repeat yourself, and can easily maintain your code. NSObject contains really useful methods such as 'description' which can do all kinds of things.

In our example we might have methods such as 'wake up' and 'sleep', but these behaviours are not limited to humans, all living things do this (I should think), so maybe we could create a class called 'Animal'. In the animal class we could have methods such as wakeUp and fallAsleep, and then we could sub class it and make our person class inherit from it. Lets see the PHP way of doing just that.

Class Animal {
	private $awake = false;

	public function wakeUp(){
		$this->awake = true;
	}
	
	public function fallAsleep(){
		$this->awake = false;
	}
}

Class Person Extends Animal {
	public $name;
	
	public function starJump(){
		echo $this->name . ' did a star jump!';
	}
}

$me = new Person();

$me->wakeUp();
$me->name = 'Tom';
$me->starJump();

Don't worry about the syntax too much if you're not familiar with it; but here we can see that we have 2 classes. Our first is 'Animal' which has the methods we said we'd create, and the second is 'Person' which allows us to do a star jump - I've never seen a monkey do one of those, so I think we're safe to keep that within our own species for now. We then create a new object based on the person class, and immediately call the 'wakeUp' function - but this doesn't exist in our Person class, so what's going on?! Well because we used the keyword 'Extends' - (syntax varies from language to language) our $me object has access to all the methods implemented in our Animal class. And that's inheritance.

Encapsulation

Last but not least is this badboy. The term is means when we take the data (instance variables/ivars) and instructions (methods), and put it all within a class. When we do this we make our objects self-sufficient. Think about it like so. Without encapsulation our person class might have to be operated on by another function outside of our class to, say for instance, make a curry. So it might send a bunch of messages (that's just calling the methods of a class), to our object, and fiddle around with our public instance variables. That way of doing things will get the job done. But, and it's a big but, it ain't good practise!

If you were working on a project where your people objects had to be able to make a curry (maybe it's a restaurant game), and you wrote your curry method outside of your person class it would work. But then what happens if you start a new project, and the people objects in that scenario need the curry shizzle?! Bad things start to happen, that what happens. So let it be known, objects should know what they are doing without needing help (anything beyond variable data), from the rest of your program. Maybe you decide not all people should need to know how to make a curry (plain craziness quite frankly), it would be a better idea to sub-class the Person object to something like a 'Chef' class - using your handy friend inheritance .

And with that we have finished with the main concepts of OOP. As you can see above, most of the A PIE concepts work together to create a beautiful paradigm (to a programmer at least), and one that will ensure you consistently write good quality code. Although this has been written from the perspective of web development, should you ever wish to move into complied programming languages such as Objective-C for iOS, you will find that they are heavily class based, so you've learnt something that should serve you well in the future - well done you!

* I am by no means suggesting that you objectify men or women.

Generate a calendar with PHP

Note: This article has been marked for a quality review and will soon be updated.

Calendars are useful for a wide variety of things, least of all planning and recording events that are going to happen in the future, and while it may not be obvious at first, there a are a number of challenges in creating a dynamic calendar with PHP. In this tutorial I will show you the basics of what you need to get started. See an example of what we will be creating here.

Let's first think about what we are creating. We want a standard calendar that will display dates month by month, and in this tutorial we will make it dynamic as to display the current month, and highlight the current day. But unfortunately this isn't as simple as printing out 31 days and labelling them up. Because calendars show dates preceding and succeeding the month, we need to display our data based on the day of the week that the month starts on, this is something we need to think about when designing the code. Not all months have 31 days in them either, so we need to build a system which adapts to each month.

Let's take a look at the PHP. First we will gather all the information we need about the month - we will be using the current month, but you could change the values of the following variables based on your needs.

$today = date("d"); // Current day
$month = date("m"); // Current month
$year = date("Y"); // Current year
$days = cal_days_in_month(CAL_GREGORIAN,$month,$year); // Days in current month

$lastmonth = date("t", mktime(0,0,0,$month-1,1,$year)); // Days in previous month
		
$start = date("N", mktime(0,0,0,$month,1,$year)); // Starting day of current month
$finish = date("N", mktime(0,0,0,$month,$days,$year)); // Finishing day of  current month
$laststart = $start - 1; // Days of previous month in calendar

Okay, so the code above utilises some inbuilt functions and stores al the data we need. Firstly we get today's date using PHP's date() function, having this will allow us to highlight the current day. We then collect the current month, year, and the number of days in the current month. All pretty standard so far. Then we go on to get the number of days in the month preceding the current month, as well as both the start and end date of the current month. We can use those variables to figure out an offset so that we can display the day on which the current month started correctly.

To that we will add the logic that will actually display the calendar:

$today = date("d"); // Current day
$month = date("m"); // Current month
$year = date("Y"); // Current year
$days = cal_days_in_month(CAL_GREGORIAN,$month,$year); // Days in current month

$lastmonth = date("t", mktime(0,0,0,$month-1,1,$year)); // Days in previous month

$start = date("N", mktime(0,0,0,$month,1,$year)); // Starting day of current month
$finish = date("N", mktime(0,0,0,$month,$days,$year)); // Finishing day of  current month
$laststart = $start - 1; // Days of previous month in calander

$counter = 1;
$nextMonthCounter = 1;

if($start > 5){	$rows = 6; }else {$rows = 5; }
for($i = 1; $i <= $rows; $i++){
	echo '<tr class="week">';
	for($x = 1; $x <= 7; $x++){				
		
		if(($counter - $start) < 0){
			$date = (($lastmonth - $laststart) + $counter);
			$class = 'class="blur"';
		}else if(($counter - $start) >= $days){
			$date = ($nextMonthCounter);
			$nextMonthCounter++;
			
			$class = 'class="blur"';
		
		}else {
			$date = ($counter - $start + 1);
			if($today == $counter - $start + 1){
				$class = 'class="today"';
			}
		}
				
			
		echo '<td '.$class.'><a class="date">'. $date . '</a></td>';
		
		$counter++;
		$class = '';
	}
	echo '</tr>';
}

Let's go over what that does. To begin with we figure out how many rows we are going to need by checking to see if the start day is greater than a Friday; if it is, we have 6 rows, otherwise we have 5. We then have a nested loop - one for the weeks, and one for the days in the weeks. Looking at the code we can see that the first loop runs as many times as there are rows, while the inner loop always loops 7 times. Then we have a fancy if statement to give us our date. In plain English, this is what it does: if the number of days already processed, take the starting day of the current month is less than 0, output a day from the last month - this makes sure we fill in the gaps, so if the current month started on a Tuesday, this code would get executed on the first iteration to display last month's Monday. If not, is the day in question part of next month? If so output the day with it's own date - nice an simple because all months start from 1.

And then we come to the last part of the if statement, which will be executed if the day in question is part of the current month. If it is today's date we give it a class of "today". Then we output the variables, increment our counter variable to keep track of the current day, and reset our $class variable.

So to put it all together within a table we would have:

<section id="content" class="planner">	
<h2><?php echo date("F Y") ?></h2>

<table class="month">
	<tr class="days">
		<td>Mon</td>
		<td>Tues</td>
		<td>Wed</td>
		<td>Thurs</td>
		<td>Fri</td>
		<td>Sat</td>
		<td>Sun</td>
	</tr>
<?php 
		
	$today = date("d"); // Current day
	$month = date("m"); // Current month
	$year = date("Y"); // Current year
	$days = cal_days_in_month(CAL_GREGORIAN,$month,$year); // Days in current month
	
	$lastmonth = date("t", mktime(0,0,0,$month-1,1,$year)); // Days in previous month
	
	$start = date("N", mktime(0,0,0,$month,1,$year)); // Starting day of current month
	$finish = date("N", mktime(0,0,0,$month,$days,$year)); // Finishing day of  current month
	$laststart = $start - 1; // Days of previous month in calander
	
	$counter = 1;
	$nextMonthCounter = 1;
	
	if($start > 5){	$rows = 6; }else {$rows = 5; }

	for($i = 1; $i <= $rows; $i++){
		echo '<tr class="week">';
		for($x = 1; $x <= 7; $x++){				
			
			if(($counter - $start) < 0){
				$date = (($lastmonth - $laststart) + $counter);
				$class = 'class="blur"';
			}else if(($counter - $start) >= $days){
				$date = ($nextMonthCounter);
				$nextMonthCounter++;
				
				$class = 'class="blur"';
					
			}else {
				$date = ($counter - $start + 1);
				if($today == $counter - $start + 1){
					$class = 'class="today"';
				}
			}
				
			
			echo '<td '.$class.'><a class="date">'. $date . '</a></td>';
		
			$counter++;
			$class = '';
		}
		echo '</tr>';
	}
	
?>
</table>
</section>	

If you wanted to add things like 'st' to each date, or even the day to each date you could use a case statement to switch on the $x variable - 1 being Monday, 2 being Tuesday, and so on. And that's that! Don't forget to style the classes that I added such as "blur" to those days that don't fall in the current month, as well as "today" to, well I'm sure you can figure that one out 😉 And as always check out the demo here.

WordPress: Load more posts on page scroll

Note: This article has been marked for a quality review and will soon be updated.

Although I don't visit archive pages very often, when I do I like it when I don't have to trawl through pages and pages of 10 posts using tiny navigation buttons at the bottom of the page. A great way to prevent this annoyance for your users is to use AJAX to dynamically append posts to the end of your archive list. To do this in WordPress we need to abstract the process of getting the list of posts and then use some Javascript (in out case jQuery aided) magic to load in our content. So lets get started.

First off we need to create a function that we can call to spit out a list of posts. Usually on an archive page we would use the normal WordPress loop to accomplish this, but in our case we need to abstract the loop into a separate function so that we can access it from any file - more specifically our Javascript file. We also need to be able to pass an offset value to this function to make sure we don't load the same posts every time it is called. This function is going to differ slightly depending on your markup for your archive page, but this is how it would look for Tom's Big Box:

function getArchives($count,$offset){
	query_posts('posts_per_page='.$count.'&offset='.$offset);
	
	$posts = array();

	if(have_posts()) : while(have_posts()) : the_post(); 	
		$img = post_image($post->ID);
		$commentsNo = get_comments_number();
		if($commentsNo==0){
			$comments = 'No Responses';
		}else if($commentsNo==1){
			$comments = '1 Response';
		}else {
			$comments = $commentsNo . ' Responses';
		}
		
		$item = '<li id="'. get_the_ID() .'">
			<figure class="vignette left">
				<img src="'. get_bloginfo('template_url') .'/scripts/timthumb.php?src='. $img->src .'&w=180&h=120" alt="'. $img->alt .'" />
			</figure>
			<h3><a href="'. get_permalink() .'">'. get_the_title() .'
			<p class="article-meta left">'. get_the_time('jS M Y',$post->ID) .' ~ '. $comments .'

<p class="extract"> '. get_the_excerpt() .' </p> </li>'; array_push($posts,$item); endwhile; endif; return $posts; }*/

Stick this in your functions.php file, and we can walk through what this code is doing. Firstly the two parameters that we it accepts are $count - which tells our functions how many posts we want, and $offset - to ensure that we don't load the same posts every time our function is called. We then send these parameters to WordPress's query_posts() function which will give us a list of posts. We then set up the $posts array to sold our data and begin iterating through the posts. I created a separate image variable to hold information about each post's image because I don't use WordPress's inbuilt image resizing, this is something which may not apply to you. After that an if statement creates a nice string based on the number of comments per post - this is because the inbuilt functions return only the number of comments or directly outputs to the document - something we don;t want. Then we load our content into the $item variable using whatever markup we need, and finally use array_push() to add our $item variable to the $posts variable, before returning the final $posts variable in its entirety.

Phew! Well that's most of the server-side stuff done, but before we can say goodbye to PHP, we need to do one more thing. We need to create a file to which we will pass our parameters, and that will execute the function we just created, and return the code we need. Don't worry, this is far simpler than the function above, let's take a look at the code:

require( '../../../../wp-load.php' );
$posts = getArchives(20,$_GET['offset'],false); 
foreach($posts as $p){
	echo str_replace("'","'",$p);
}

So, ignoring the first line for a moment, this file simply passes the $_GET['offset'] variable to our newly created function, and then iterates over the output, making sure to replace any single quotation marks to stop it from breaking. "But hang on Tom, what does that first line do?!" I hear you cry, well the first line makes sure we can access the function we just created, and for that matter all the inbuilt WordPress functions, so it is vital that you keep it. You will also need to change the path in the require() statement to ensure it matches the root directory of your WordPress install. Pop the above code in a file called get-posts.php and stick it in your theme's directory. And with that, we can say hasta la vista to PHP, and buongiorno to jQuery (that's right, I'm cultured).

Now, having made sure jQuery is included on your page, paste in the following code:

var halfWay = ($(document).height()/2);
var offset = 20;
var inAction = false;
var reachedEnd = false;

$(document).scroll(function(){
   if($(document).scrollTop() > halfWay && inAction == false){
       inAction = true;
		
       $('.article-list').append($('
').load('http://example.com/wp-content/themes/myTheme/get-posts.php?offset='+offset, function(){ offset = offset + 20; halfWay = halfWay + 1775; inAction = false; })); } });

Lets go through what this does. We have a function that fires whenever the page scrolls, and within that we compare the current scroll amount to half the overall document height, if it is greater (meaning that the user has scrolled more than half way down the page), and the variable inAction (I'll get to that in a moment) is true, it executes the following code. If the conditions are satisfied we then use AJAX to load in some more posts. Now it may appear a rather convoluted way to be doing so, but in my experience this way of handling an AJAX request of this type is the best. So for this method we send a request to our file that we just created in our theme's directory, and pass it the variable offset, when the content is loaded we run the embedded function which increments our offset variable by 20, adds a suitable amount to our halfWay variable. We then reset the inAction variable. This variable is used to prevent a massive build up of requests because of page scrolling, we use it because every time the page scrolls even a pixel, the function is called, so we don't want it to be called 3 times before we have a chance to offset the next post, otherwise we will end up with a huge amount of duplicate posts being loaded in. The conditions in the if statement will stop being satisfied after the last posts are loaded in because our inAction will stay in it's true state forever after one request for no posts means the success() function isn't executed.

And that's it! It might be a good idea to have a loading graphic at the bottom of you page when doing this to give some user feedback, and I would suggest also adding pagination just incase your server stops responding and leaves your users hanging. But aside from that, I think I covered the basics of how to implement the AJAx loading in of content. Oh and by the way, you will now also be able to generate archives anywhere on your site using the function getArchives(), meaning you will write less code in the long run - two birds with one stone!

Build an uploader for S3

S3 is Amazon's "Simple Storage Service" for hosting content on the web. It allows developers to offload static content to their powerful content delivery network at low cost, to improve site performance. I've used S3 on a number of projects to host content, but one thing that only recently cropped up wad the notion of allowing users to upload their own content to the service from within any given site. To accomplish this I had to use a little bit of everything, including PHP and jQuery. But don't worry, if you don't want to use jQuery, this technique should still apply to other implementations.

As I said we will be using jQuery for this, and more specifically, the fantastic plugin Uplodify - a set of files that will enable simple uploading, and that will handle all the heavy lifting of file manipulation. So go ahead and download/unzip Uplodify, and then stick it on your server. I then used the following standard HTML to display the upload button.

<div id="upload_box">
	<div id="file_upload" name="theFile"></div>
</div>

Having done that, make sure to include jQuery, swifobject.js, and jquery.uplodify.[VERSION].js, and then add the following JS.

<script type="text/javascript">
    $(document).ready(function() {
      $('#file_upload').uploadify({
        'uploader'  : 'uploadify.swf',
        'script'    : 'uploadify.php',
        'folder'    : 'uploads',
        'multi'	: true,
        'fileExt'   : '*.jpg;*.gif;*.png',
        'auto'      : true,
        'buttonImg' : 'button.jpg',
        'width'	: '86',
        'height'	: '28',
        'onSWFReady': function(){ $("#file_upload").show(); },
      });
      
    });
</script>

And that's the basic configuration needed to get Uploadify working. Now we need to enlist the help of a PHP class to enable us to interface with S3. That class allows you to do some pretty advanced stuff, and is a great solution all round for working with S3. In our case you just need to download that that and pop it in the same directory as the file uplodify.php.

And now we are finally ready to add the functionality that we've all been waiting for. Open uplodify.php and change:

move_uploaded_file($tempFile,$targetFile);
echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile);

to:

$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile =  str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];

 $fileTypes  = str_replace('*.','',$_REQUEST['fileext']);
 $fileTypes  = str_replace(';','|',$fileTypes);
 $typesArray = split('\|',$fileTypes);
 $fileParts  = pathinfo($_FILES['Filedata']['name']);

 if (in_array($fileParts['extension'],$typesArray)) {
	
	if (!class_exists('S3'))require_once('S3.php');
	
	//AWS access info
	if (!defined('awsAccessKey')) define('awsAccessKey', '[ACCESS KEY]');
	if (!defined('awsSecretKey')) define('awsSecretKey', '[SECRET KEY]');
	
	//instantiate the class
	$s3 = new S3(awsAccessKey, awsSecretKey);

	//move the file
	$s3->putObject($_FILES['Filedata']['tmp_name'], "[BUCKET NAME]", $_FILES['Filedata']['name'], S3::ACL_PUBLIC_READ);


	echo "http://s3.amazonaws.com/[BUCKET NAME]/".$fileName;
 } else {
 	echo 'Invalid file type.';
 }

So what we've done there is replaced the part of the code that previously moved the uploaded file (with the imaginatively named move_uploaded_file() function), with some code to invoke a move to your S3 bucket. As you can see in the code above, the functions require some information that you will need to provide yourself such as your secret key - this can be found by logging in here.

And that's that! As I said above the class can be used for more advanced manipulation of your S3 buckets and account, so do go and explore some of the things you can do with that, and have fun uploading!

Replacing the […] in WordPress

Some of you might be wondering what I mean by the [...], well I am of course referring to the symbol generated by WordPress upon calling the function the_excerpt(). Now personally I really dislike the symbol which is generated as it often doesn't fit with my design, and I always prefer to have an ellipse - ... followed by a link to continue reading - but how on earth could we go about doing this? Does the answer lie in using jQuery to find and replace this horrendous symbol? Perhaps we need to add some arguments to the the_excerpt() function?

No, it's far simpler than that.

All that needs to be done is the addition of some code to the functions.php file in your theme directory. So head over to this file (if it doesn't exist, create it) and go to your next free line, and copy and paste the code from below.

function new_excerpt_more($post) {
	return '...</p><a href="'. get_permalink($post->ID) . '">' . 'Continue Reading...' . '</a>';
}
add_filter('excerpt_more', 'new_excerpt_more');

So the above code replaces the default [...] with something that looks like "... Continue Reading...", where the continue reading text is a link to the article itself. You could replace this with whatever code you like and have bundles of fun if you like that kind of thing. Just remember to not leave any blank lines at the bottom of your functions.php file as this can cause errors later down the line.

Why you should be using PHP

Note: This article has been marked for a quality review and will soon be updated.

I would like to introduce you to PHP. If you aren't already using PHP on your site, you should be! PHP is an easy way of generating dynamic content and interacting with all sorts of things, from the server, to the user, right back to databases. In past tutorials I've used PHP without first explaining why, in this article I'll explain why it's really great. It's important to note that you need PHP installed before you start using it, you can do so by either using a server (the easiest, but more expensive way), or by searching Google for "install PHP on OSX/Windows".

With CSS we can use a small bit of code to link our HTML pages to our style sheets - the meta tag. Well what if you're building a site and you want the same header on every page, without PHP you would just have to copy and paste the same code onto every page, and imagine if you had 100 pages when you decided you wanted to change a tiny detail. That would be a problem. But we can solve this problem with PHP using a simple require() function. For example...

<?php 
  require("header.php");
?>

The above code simply goes and grabs the file in between the quotations and replaces itself with it's contents. This can be really useful, and means that you only have to edit the one file to see your changes reflected across your site. But PHP is so much more than just something you can use to insert files, you can use it to do (nearly) anything!

PHP was originally created to produce dynamic content, the PHP code tells the server to do something and returns a HTML value. So say for instance, you may have once visited a site that was displaying the current time or/and date. There are many ways to do this, but one of the easiest, is with PHP. Let me show you.

<?php 
  echo gmdate('d-m-y / H:i'); 
?> 

Would output something like this: 31-01-10 / 19:23. The "echo" command basically produces text and sends it to the browser for rendering, while the gmdate() function gets the current GMT time. The code it encased with the two <?php ?> markers, which tell the server that it should look out for PHP to render. PHP is a powerful language which you can use for a plethora of solutions. My favourite part of PHP is the community. If you want to do something in PHP you will be able to find the solution easily. Furthermore it seems to me like the is a function for everything - want to know when a file was created? There's mktime() for that. Want to capitalise the first letter of a string? There's ucwords() for that! Want to make a cup of coffee? There's makeMeCoffee()! Well that last one may have been a bit of wishful thinking, but there really are a huge amount of functions that you can utilise off the shelf.

PHP is also really useful for security. If you've got a password that you want to encrypt, you can use the md5() function, which creates an incredibly secure hash which is nearly impossible to decrypt. Moreover, if you want to ensure only certain visitors can access certain pages, you can use $_SESSION[] variables to store bits of information accessible by any page of your site. Lastly, PHP can be used for databases, there is a detailed explanation of this over in my tutorial on building a CMS, and I believe it is one of the most useful features of PHP.

PHP is a really powerful programming language, and I recommend you learn it. A site I found very useful when I was starting off was Tizag, which will walk you through the basics. And when you're trying to solve a problem, sooner or later you'll end up over at PHP.net which is a fantastic resource, despite the slightly 90s look and feel to the site :).

I use PHP all the time, as do solutions such as WordPress and Facebook. It makes my life so much easier and opens up doors to things that I could never achieve without it. I urge you to learn it, and as always the best way to learn is through using the language, so go ahead and create something cool using PHP!