Build a Blog – Tips and Tricks

A few tips and tricks shared by users on the old CodeGrrl forums over the years, to help you customise your blog.

Jump to:

Please note: The Build-A-Blog series is an introduction to creating a simple blog script using PHP. These tutorials are meant to help you to learn PHP and MySQL and to use these to fetch and store data and display it on a web page. These tutorials should not be used ‘as is’ on a production website – especially if you are new to PHP and do not understand what you are doing. We would recommend that you try the B-A-B series on a safe, development environment – such as an offline installation of PHP and MySQL – so you can learn how everything works.

GWG and its staffers accept no responsibility for anything that may (or may not) happen to your site or server as a result of you using these tutorials – you do so AT YOUR OWN RISK.

Archive by month

Change this part in your archive list page:

$result = mysql_query("SELECT FROM_UNIXTIME(timestamp, '%Y') AS get_year, COUNT(*) AS entries FROM php_blog GROUP BY get_year");

To this:

$result = mysql_query("SELECT FROM_UNIXTIME(timestamp, '%M %Y') AS get_month, COUNT(*) AS entries FROM php_blog GROUP BY get_month ORDER BY timestamp ASC"); 

(Note: If you want your most recent entries first, change ASC to DESC in the query above)

Next, change this:

while ($row = mysql_fetch_array($result)) {
    $get_year = $row['get_year'];
    $entries = $row['entries'];

    echo "<a href=\"archives.php?year=" . $get_year . "\">Entries from " . $get_year . "</a> (" . $entries . ")<br />";

To this:

while ($row = mysql_fetch_array($result)) {
	$get_month = $row['get_month'];
	$entries = $row['entries'];
	echo "<a href=\"archives.php?month=" . $get_month . "\">Entries from " . $get_month . "</a> (" . $entries . ")<br />";

Then, in your archive display page, change this:

$result = mysql_query("SELECT timestamp, id, title FROM php_blog WHERE FROM_UNIXTIME(timestamp, '%Y') = '$year' ORDER BY id DESC");

To this:

$result = mysql_query("SELECT timestamp, id, title FROM php_blog WHERE FROM_UNIXTIME(`timestamp`, '%M %Y') = '" . mysql_real_escape_string($month) . "' ORDER BY id DESC")

And this:

if (!isset($_GET['year'])) {
    die("Invalid year specified.");
else {
    $year = (int)$_GET['year'];

To this:

if (!isset($_GET['month'])) {
    die("Invalid month specified.");
else {
    $month = htmlentities(strip_tags($_GET['month']));

Remember to change any other parts that say $year in your page to $month too.

Spam protection

Tip 1: Based on Jem’s original BellaBook spam protection.

In your individual entries page, put this just after the comment box, but before the submit button:

<script type="text/javascript">
document.write('<input type="hidden" name="spamtest" id="spamtest" value="SPAMWORD" />');

Change SPAMWORD to something random, no one will have to remember this so make it as complicated as you like.

Then, in process.php, find this part (should be right at the top):

if (isset($_POST['submit_comment'])) {

Add this underneath:

if (!isset($_POST['spamtest']) || $_POST['spamtest'] != "SPAMWORD") {
   exit("<p>JavaScript must be enabled to comment here due to spam restrictions in place.</p>");

Again, replace SPAMWORD with the word you used earlier.

Tip 2: Simple maths problem

Add a new field to your comments form with a sum of your choice, e.g. 1+2.

1+2 = <input type="text" size="5" name="sumtest" id="sumtest" />

Then, in process.php, add this in the same place as for tip 1 (under the first two lines):

if (!isset($_POST['sumtest']) || $_POST['sumtest'] != 3) {
    exit('<p>Sorry, the answer to the maths problem was not correct.</p>');

You can change the sum whenever you want, just remember to change the answer (in this case 3) in process.php.

Note that these are extremely simple spam prevention measures and spammers may learn to get around them eventually. You can use both tips together – it doesn’t matter which bit comes first in process.php as long as they are both there.

Remove redirection after updating a post

If you would like to go back to the edit page after saving an entry, instead of to the entry itself, try the following:

Find this line:

header("Location: journal.php?id=" . $id);

Change it to:

header("Location: update.php?id=" . $id);

Where update.php is the name of your update page. Note: the page will appear to have just refreshed when you save your entry, but it will have been saved (check the contents of your entry to make sure!).

Comment notification emails

Find this line in process.php:

$result = mysql_query("INSERT INTO php_blog_comments (entry, timestamp, name, email, url, comment) VALUES ('$entry','$timestamp','$name','$email','$url','$comment')");

Add this underneath:

    $youraddress = "YOU@YOURSITE.COM";
    $emailsubject = "New comment on entry #" . $entry;
    $bodyemail = "A new comment was posted on entry #" . $entry . " of your blog. The comment was made by " . $name . " (" . $email . "; " . $url. ") on " . date('d.m.y \a\\t H:i',$timestamp) . " and their message was "" . $comment . "".";
    $extra = "From: YOUR SITE NAME <" . $youraddress . ">\r\n" . "X-Mailer: PHP/" . phpversion();
    mail($youraddress, $emailsubject, $bodyemail, $extra);

Change items in uppercase, such as the email address and YOUR SITE NAME. If you would like to change the date/time format, change this part:

date('d.m.y \a\\t H:i',$timestamp)

Change the letters in the first part (i.e. d.m.y \a\\t H:i – leave the rest as it is or it won’t work) using the guide on

Show an excerpt of a post with read more link

Open up the main page of your blog, find the following code:

    $title = stripslashes($row['title']);
    $entry = stripslashes($row['entry']);
    $password = $row['password'];
    $id = $row['id'];

And beneath that paste this code:

if (strlen($entry) > 90) {
    $entry = substr($entry, 0, 90);
    $entry = "$entry... <br /><br /><a href=\"journal.php?id=" . $id . "\">read more</a>";

This is set to show an excerpt of 90 characters of the post. If you would like to show more (or less), just change 90 to another number.

Emoticons and BBCode

Note: this is for comments only.

Find this part in journal.php:

$sql = "SELECT * FROM php_blog_comments WHERE entry='$id' ORDER BY timestamp";
$result = mysql_query ($sql) or print ("Can't select comments from table php_blog_comments.<br />" . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
    $timestamp = date("l F d Y", $row['timestamp']);

Add this below:

$bbcode = array('[b]', '[i]', '[u]', '[/b]', '[/i]', '[/u]');
$bbcode_replace = array('<b>', '<i>', '<u>', '</b>', '</i>', '</u>');

$emoticons = array(":)", ":(", ":'(", ";)", ":P", ":o", ":D");
$emoticons_replace = array(
    '<img src="smile.gif" alt=":)" />',
    '<img src="sad.gif" alt=":(" />',
    '<img src="cry.gif" alt=":\'(" />',
    '<img src="wink.gif" alt=";)" />',
    '<img src="tongue.gif" alt=":P" />',
    '<img src="shocked.gif" alt=":o" />',
    '<img src="happy.gif" alt=":D" />'
$formatted_comment = str_replace($bbcode, $bbcode_replace, stripslashes($row['comment']));
$formatted_comment = str_replace($emoticons, $emoticons_replace, $formatted_comment);

Replace the parts in the <img src=""> parts with the correct URLs to your images (note you will need to have images already, we can’t provide these for you!). Feel free to add more emoticons, just add more options to the $emoticons part (before the ‘);’ – make sure to separate each one by commas and and enclose them in quotes). Add its corresponding image in a new line to the $emoticons_replace part, before the ‘);’ at the bottom. Each line should have a comma at the end EXCEPT the last line, and each line should be surrounded by quotes (I have used single quotes so as not to interfere with the double quotes used in the HTML). Same goes for the BBCode – feel free to add more items you want to allow, such as [code] or [quote]. Remember to add the closing tags as well, or your comments page will look very messy!

Note: it is very important that you specify the images and replacement HTML code in the same order that you specified the image and bbcode codes, otherwise you will get the wrong image/HTML replacement in your comments!

When you have done that, find this part in journal.php:

print("<p>" . stripslashes($row['comment']) . "</p>");

Change it to:

print("<p>" . $formatted_comment . "</p>");

RSS Feed

See this forum post for details on how to create a feed for your blog.