Building a CMS Part 1
A content management system (or CMS) is the best way (I think) to maintain a site. This site, like many others uses WordPress, a blogging CMS. There are many options available to us web designers out there, but I think creating your own CMS is a really good way of learning a lot of new techniques. So let me tell you what you will learn in this series. We will be starting from scratch, laying out our plans for what we want to achieve with our CMS and how we are going to go about doing it. We will then set up a database for our CMS and make it accessible to a bunch of PHP based pages. We will then create a site that relies on the CMS to display content, and at the same time create the back-end of the CMS where we will be able to add pages, change the content, and upload images. At the end of these tutorials you should have a good idea of what it takes to create a CMS and hopefully appreciate even more, the work of those who maintain services such as WordPress.
What do I need to know?
- General Understanding of HTML / CSS
- Basic knowledge of PHP and MySQL syntax
- Access to a server with a MySQL Database & PHPMyAdmin
Once you have all of the above we should be able to get going.
Let's do this thing!
Our CMS is going to be rather simple, but will allow for user sign-up, content editing and a few other little features. The backbone of our CMS is going to be our database, and we are going to use PHPMyAdmin to create one. If you have a hosting plan you will need to find out if you have PHPMyAdmin installed on your server - most hosts should offer the service - including Media Temple (shameless plug
). Many services require you to create the database outside of PHPMyAdmin, so find out how to do so and create one called "main" (all lower-case). Then head over into PHPMyAdmin and select the database on the left. Click "Create New Table" with 6 fields named "content". These fields will be id, page, title, text, lastupdate, updater - exactly like that. Make them all VARCHARs with appropriate lengths.
The next table is to be even more in-depth, it's the users table. Go ahead and create a new table named "users" with 13 fields. They will be - id, username, password, email, hash, active, firstName, lastName, firstLogin, lastLogin, secretQuestion, secretAnswer, photo. Don't worry - all will be explained with a couple of handy lists below.
- id - for internal referencing, which is a necessity
- username - what users will use to login
- password - what users will use to authenticate themselves
- email - for communication with the user
- hash - to validate the user's email address
- active - to make sure the user has activated their email
- firstName - so we know what to call them informally
- lastName - so we know who we have on record
- firstLogin - just a nice little piece of information
- lastLogin - to find out if they are using their account
- secretQuestion - if they forget their password
- secretAnswer - the answer to the one above
- photo - so we can see them!
Right, now we know what is what in the land of databases, we need to connect to it. So make sure you have the required credentials to access the database. These are your database user name, your database password and your database name (and very rarely your hostname). Once you've got all of that good stuff head over into your code editor of choice and let the mayhem begin!
Our Connect File
To have a CMS work, we need to be able to communicate with our database, and to do so we will first have to connect to it. And if we want multiple pages of our CMS to be able to communicate with our database we are going to need to create a separate file (the alternative to this, is copying and pasting the code onto every page - but that's a lot of work, and if we happen to change any of the details, a whole lot more). The file itself is really simple, below is the code for the file. Create a new file called connect.php and paste in the code below.
$dbhost = 'localhost'; // You shouldn't need to change this
$dbname = 'db82542_main'; // The name of your database
$dbuser = 'userName'; // Your username
$dbpass = 'password'; // Your password
mysql_connect($dbhost, $dbuser, $dbpass) or die("Error connecting to Database");
mysql_select_db($dbname) or die("Unable to select Database");
?>
We will now be able to use the PHP function of require to include this in all the files we create. Before we continue, make sure that the file can successfully connect to the database, do this by simply visiting the page. If successful you should see a blank page, if not, you should see an error message. Make sure it works before continuing on.
User Authentication
We want to be able to edit the content of our site right? But what we don't want, is everybody being able to edit the content, or else we could be subject to spammers, hackers, and all kinds of other nasty stuff. So we are going to have to create a user system. You might think this is a long and complex process, but really it's quite simple. We will need to create a login page, followed by one to authenticate the credentials, followed by a "Members Only" area where we will eventually place the main body of our CMS. So let's get started.
Create a new page named login.php and insert a basic page structure. Now we need to create a form that users can use to login. The form is going to be very simple with inputs for username, password, and then a submit button.
<form id="login" action="userauth.php" method="post">
<label for="username">Username: </label><br />
<input class="textbox" type="text" name="username" value="" />
<br />
<br />
<label for="password">Password: </label><br />
<input class="textbox" type="password" name="password" value="" />
<br />
<br />
<input type="submit" class="submit" value="Submit" />
</form>
As you can see from the code above we are going to be needing another file named userauth.php, this will be the file that will compare what the user inputs to what we have in our database, so go ahead and create it. So what do we have at the moment? Well we have a login form that posts the information to another page to validate it. Right now if you fill in the form you will be taken to a black page, and that's no good is it?! So let's create the authentication page. Hopefully you've already created the file, open it up and insert the following code (a basic page structure fo this page isn't required).
require("connect.php");
session_start();
$iusername= mysql_real_escape_string($_POST['username']);
$ipassword = mysql_real_escape_string(md5($_POST['password']));
if(empty($iusername) || empty($ipassword)){ echo "<meta http-equiv=\"refresh\" content=\"0;url=http://yoursite.com/login.php?m=1\">"; }
$result = mysql_query("SELECT * FROM users WHERE username = '".$iusername."'");
$row = mysql_fetch_array($result);
$dbusername = $row['username'];
$dbpassword = $row['password'];
if($iusername == $dbusername && $ipassword == $dbpassword) {
$_SESSION['loggedin'] = '1';
$_SESSION['username'] = $iusername;
$_SESSION['password'] = $ipassword;
$_SESSION['firstname'] = $row['firstName'];
$_SESSION['lastname'] = $row['lastName'];
$_SESSION['userid'] = $row['id'];
$_SESSION['photo'] = $row['photo'];
$_SESSION['usertype'] = $row['userType'];
$_SESSION['email'] = $row['email'];
$_SESSION['firstlogin'] = $row['firstLogin'];
$_SESSION['lastlogin'] = $row['lastLogin'];
if(empty($dbusername)){
echo "<meta http-equiv=\"refresh\" content=\"0;url=http://yoursite.com/login.php?m=1\">"; session_destroy(); echo '1';
};
if($row['active']==0){
echo "<meta http-equiv=\"refresh\" content=\"0;url=http://yoursite.com/login.php?status=noneactive\">"; session_destroy();
};
if($row['firstLogin'] == 0){
mysql_query("UPDATE users SET firstLogin='$date' WHERE username='$iusername'");
};
mysql_query("UPDATE users SET lastLogin='$date' WHERE username='$iusername'");
echo "<meta http-equiv=\"refresh\" content=\"0;url=http://yoursite.com/index.php\">";
}
else {
echo "<meta http-equiv=\"refresh\" content=\"0;url=http://yoursite.com/login.php?m=1\">";
session_destroy();
}
?>
Right so let me explain the code above (if you get what it's doing feel free to skip this explanation) So at the top of the code we can see that we require our connect.php file which allows us to connect to our database (note: if connect.php doesn't exist the page will stop working!) then we start a session, this will be for a set of variables we want other pages to be able to access. After this we assign values to 2 variables and use the PHP function of mysql_real_escape_string() which protects us from MySQL Injection which is a very nasty thing indeed! Then we fetch some results from our database and set up two more variables so that we can compare them. Then we use an "if" statement to compare the values, and if the user has entered the correct credentials we do a a few things. Firstly we set up a number of session variables to be accessed by all other pages of the site. The we check to see if the username the user actually inputted exists - if not they are redirected to the login page and we destroy the session. Then we check to see if the user has activated their email address, if not they will be redirected to the login page. If they get through both "ifs" the page then checks to see if this is the first time the user has logged in, and if so, sets the value of the record's "firstLogin" field to today's date and finally redirects the user to the index page for the member's only area. And if the username and password don't match they promptly redirected o the login page while the session is destroyed. Phew! Quite a lot to take in there, but providing you've made it this far we should be getting somewhere.
Now the more astute among you may have realised that we haven't actually got any records in our database, meaning that even if we wanted to, we wouldn't be able to login. So let's get to creating that signup form.
The Signup Form
We are going to create a really simple form so that users can signup, you should be aware that more time should be spent perfecting the form such as adding validation to certain fields and maybe some sort of terms of service agreement, but for now let's just go ahead and create a simple signup form.
<label for="username">Username: </label>
<input name="username" type="text" value="joebloggs" /><br />
<label for="password">Password: </label>
<input name="password" type="password" value="password" /><br />
<label for="email">Email Address: </label>
<input name="email" type="text" value="joe@bloggs.com" /><br />
<label for="firstname">First Name: </label>
<input name="firstname" type="text" value="Joseph" /><br />
<label for="secondname">Second Name: </label>
<input name="secondname" type="text" value="Bloggs" /><br />
<label for="secretquestion">Write a secret Question: </label>
<input name="secretquestion" type="text" value="Favourite Place" /><br />
<label for="secretanswer">Answer to secret Question: </label>
<input name="secretanswer" type="text" value="New York" /><br />
<input class="submit" type="submit" />
</form>
So the above code simple gives us a form whereby users can enter their info and submit it to our system. Again this form posts the information to another file called addaccount.php, and we need to create this file. so go ahead and create addaccount.php and paste in the following code.
require("connect.php");
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string(md5($_POST['password']));
$email = mysql_real_escape_string($_POST['email']);
$firstname = mysql_real_escape_string($_POST['firstname']);
$secondname = mysql_real_escape_string($_POST['secondname']);
$secretquestion = mysql_real_escape_string($_POST['secretquestion']);
$secretanswer = mysql_real_escape_string($_POST['secretanswer']);
$hash = rand(1000000, 99999999999);
mysql_query("INSERT INTO users(id, username ,password, email, hash, active, firstName, lastName, firstLogin, lastLogin, secretQuestion, secretAnswer, photo) VALUES(NULL,'$username', '$password', '$email', '$hash', '0', '$firstname', '$secondname', '0', '0', '$secretquestion', '$secretanswer', '0')") or die('Unable to insert Data' . mysql_error());
$message = '
<html>
<body bgcolor="#FFF">
<p style="font-family:Calibri, Arial, Helvetica, sans-serif; color:#000; font-size:16px;">Hi ' . $firstname . ', You have just signed up for your account on my website. To activate the account please click, or copy and paste into a browser, the link below.</p><br /><br />
<p>http://tomsbigbox.com/examples/cms/activate.php?i='.$hash.'&email='.$email.'</p>
</body>
</html>';
$subject = 'My CMS – Please Activate your Account';
$headers = 'From:My Site!' . "\r\nContent-Type: text/html\n";
mail($email, $subject, $message, $headers);
echo "<meta http-equiv=\"refresh\" content=\"0;url=login.php?m=1\">";
?>
Right, there certainly is a lot of code there, allow me to explain (again feel free to skip). So at the top we assign value to a set of variables and use the mysql_real_escape_string() function to prevent MySQL injection. The $hash variable will be used to validate the email address and uses the rand() function to create a random number. Next up is the mysql_query() function. Now it may look really complex, but realistically it only looks like that because we are inserting a lot of information. So all it is really is a bit of MySQL code to insert all the values into the database. After we have inserted the appropriate data we move onto validating the user's email address. To do this we need to send a message to their email address, so we'll send them a polite message explaining that they have indeed signed up for an account. The body of the message is within the $message variable. It is important to note that HTML email is very different to normal web design, so it's best to keep it simple
. Lastly we set the subject and header variables which will tell the email client to render the HTML and then redirect the user to the login page.
If the code is successful and all is well, the user should receive an email with a link to validate the page. You will need to replace the site URL with your own and create a new page called activate.php. Copy and paste the following code into this page.
require("connect.php");
$hash = $_GET['i'];
$email = $_GET['email'];
$result = mysql_query("SELECT * FROM users WHERE email ='$email'");
$row = mysql_fetch_array($result) or die(mysql_error());
if($row['active'] == 1){
echo "<h1>This account has already been activated!</h1>";
echo "<meta http-equiv=\"refresh\" content=\"2;url=login.php\">";
}
else if($row['hash'] == $hash){
mysql_query("UPDATE users SET active = '1' WHERE email = '$email'");
echo "<h1>Account Activated!</h1>";
echo "<a>You will now need to login</a>";
echo "<meta http-equiv=\"refresh\" content=\"2;url=login.php\">";
}
else{
echo "<h1>Invalid verfication</h1>";
echo "<meta http-equiv=\"refresh\" content=\"2;url=login.php\">";
}
?>
This page is self explanatory, it checks to see if the account has been activated, if not then it activates it, and if it can't find the email address, or the hash is wrong, then it doesn't activate anything! Also notice the 2 second delay on the redirects, allowing the user to read whatever message is outputted by the system.
And that's it for this first part, in the next tutorial we'll look at the member's area and how we can allow the users to edit the content of a site, as well as organising your files and making the whole thing look nice - stay tuned!
Comments
Leave a Comment
Comment Preview:
This is an example comment.

A nice simple explanation of the processes involved. Does this site use your CMS? I am developing a new website that could possibly use a CMS and await the next article with interest.
Hi Ian, no this site uses WordPress, but I had a client recently who required that I build a CMS - these tutorials are based on my experience with them, and I'm glad you like the article
I like this article but I need full tutorial on how to make a simple CMS for my blog portfolio website.
Don't worry Marjun I'm writing the next one as we speak!
[...] Building a CMS Part 1 [...]
Very helpful! Was just thinking about how to do this and am glad I found your article. Gonna go look for part two now. Thank!
Yeah, very helpful, thanks for such a nice Post