You are on page 1of 16

Creating a PHP CMS Part 1

August 10, 2009, in PHP,Programming,Web Design, by Eric Bannatyne. So far, my experience with PHP has been doing things like making small adjustments to WordPress plugins. So, I decided that it was time that I actually learn to use PHP. I thought that a good way to do this is by creating a simple CMS. In this series of posts, I will go over the steps to create a simple CMS using PHP and MySQL. I will try to explain everything, but if there is anything you don't understand, w3schools has a pretty good PHP reference, or you can leave a comment and I will do my best to help you out. I will be adding a new post in this series every Monday, Wednesday and Friday. To create a CMS you will need

A server with PHP and MySQL installed Something for viewing MySQL databases and executing queries, such as phpMyAdmin

Getting Started
The Database First of all, you will need to create a MySQL database to store information for your CMS. Once you've created it, you need to add a user to the database. After you've created the database and added a user to it, run the following SQL queries. If you're using phpMyAdmin, enter them under the SQL tab of your database.
CREATE TABLE pages ( id INTEGER AUTO_INCREMENT, title VARCHAR(150), body TEXT, DATE VARCHAR(10), PRIMARY KEY (id) );

This creates a table for storing the pages for the CMS. 'id' is a number that uniquely identifies each post. The AUTO_INCREMENT part means that each time you insert a record into the table, this number is one more than the last one. 'title' contains the title of the post. VARCHAR(150) means that it can hold a string up to 150 characters long. 'body' contains the main text for the page. 'date' stores the time that the post was written. It is 10 characters long because we will be storing the date in Unix time. Since it can only store 10 digits, it won't be able to store dates after the year 2038 problem. If anyone knows a way to fix that, please leave a comment to let me know how. PRIMARY KEY (id) means that 'id' will be a unique identifier.
CREATE TABLE settings ( name VARCHAR(20), VALUE VARCHAR(20) );

This creates a table for storing settings. It can hold a setting name, and a value for the setting. Each one can be up to 20 characters long. If you plan on expanding on the CMS later, you might want to set the values higher.

The Files After we've setup the database, we need to create some files. First, create a directory on your server that will contain these files. Create the following files, and leave them empty for now.

index.php functions.php config.php

Now, create a directory called 'admin'. This will contain all of the files for the CMS administration. In the admin directory, create these files.

index.php new.php create.php

Creating a PHP CMS Part 2


August 12, 2009, in PHP,Programming,Web Design, by Eric Bannatyne. This post is part of a series about creating a PHP CMS. Click here to start from the beginning. In this post, we will be using PHP to create a connection to the MySQL database.

Defining Constants
First, we will be defining constants for the CMS. These hold values that will not change, such as database connection information. We will define the constants in the config.php file. To define a constant, we will use the define function. This function accepts two arguments, inside of parentheses, separated by commas. The first one is the name of the constant, and the second one is the value of the constant. After a constant is defined, whenever the name of the constant is used (outside of a string), it will be replaced with its value. For example, we can define this constant.
define('CONST_NAME', 'value');

This means that whenever 'CONST_NAME' is found, without the quotation marks, it will be replaced with 'value' (this time, with the quotation marks). In config.php, define these constants. Don't forget to add <?php at the beginning of your PHP, and ?> to the end of your PHP code.

DB_NAME for the name of the database you created DB_USER for your MySQL username DB_PASS for your MySQL password DB_HOST for your database hostname (usually localhost)

Finally, define a constant called BASE_URL. The value of this constant will be the base URL for the CMS, without the trailing slash. For example, on my server, the config.php file is located at http://localhost/cms/config.php. So the value of this constant is http://localhost/cms. Now, your config.php file should look something like this. I've added in some comments to explain what the code is for.
1 <?php

2 3 4 5 6 7 8 9 10 11 12 13

// Simple CMS main constants configuration file // Database configuration define('DB_NAME', 'cms'); define('DB_USER', 'username'); define('DB_PASS', 'password'); define('DB_HOST', 'localhost'); // Base URL define('BASE_URL', 'http://localhost/cms'); ?>

Connecting to the Database


Now that we have our database connection information, we can use it to connect to the database. Whenever we do anything with MySQL, we need to connect to the database first. We will use the mysql_connect function to do this. Like define, mysql_connect also accepts arguments. However, we will be using three arguments this time. The first one is the database hostname, the second is the username, and the third one is the password.
mysql_connect('localhost', 'username', 'password');

Because we already defined constants with these values in config.php, we can use them here. We can bring the constant definitions from config.php into another file using require_once.
require_once 'config.php';

We could also use require, include and include_once. The difference between require and include is that with require, the script is stopped if it doesn't work, and with include the script continues. The ones ending with '_once' will not include the file again if it has already been included. Now, we can use the constants to connect to the database like this.
mysql_connect(DB_HOST, DB_USER, DB_PASS);

If there's a problem connecting to the database, we will need to handle it. We will use die for this. This shows a message if there is an error.
mysql_connect(DB_HOST, DB_USER, DB_PASS) or die('Could not connect. ' . mysql_error());

This would connect to the database, but if there's an error (for example, if the database password is wrong), it will display the message 'Could not connect. ' and some details on what the error is. After we've connected to the database, we need to select a database to work with, using mysql_select_db. We will only use one argument for this function: the name of the database.
mysql_select_db(DB_NAME);

Again, we will use die to handle any errors with selecting the database.
mysql_select_db(DB_NAME) or die('Could not select database. ' . mysql_error());

We can now execute MySQL queries after we've connected to the database. However, we will have to use this code in every file containing MySQL queries. To make things easier, we will create our

own function. In functions.php, enter this code.


function connect() { }

function tells us that what's coming next is a new function. The name of this function is 'connect'. The parentheses are there because our functions can accept arguments, but they are empty here because we aren't using arguments for this function. The opening curly brace marks the beginning of the function and the closing curly brace marks the end of the function. We will enter the code we just wrote to connect to the database between the curly braces. Our function should look like this now.
function connect() { mysql_connect(DB_HOST, DB_USER, DB_PASS) or die('Could not connect. ' . mysql_error()); mysql_select_db(DB_NAME) or die('Could not select database. ' . mysql_error()); }

Be sure to indent everything between curly braces. It's not necessary for it to work, but it helps make the code a lot more readable. If you aren't already, use a text editor with automatic indentation. Whenever we need to use our function, we can just use
connect();

Now we just need to include config.php at the top of functions.php. Whenever I say to include a file, use require_once unless another way would be better. Also, be sure to add comments to your code to explain what you're doing. Now, your functions.php file should be something like this.
<?php // Simple CMS main functions file require_once 'config.php'; // Connect to MySQL database function connect() { mysql_connect(DB_HOST, DB_USER, DB_PASS) or die('Could not connect. ' . mysql_error()); mysql_select_db(DB_NAME) or die('Could not select database. ' . mysql_error()); } ?>

I had originally planned to include writing to the database in this part of the series, but this post has gotten a bit long, so I will talk about that in the next post.

Creating a PHP CMS Part 3


August 14, 2009, in PHP,Programming,Web Design, by Eric Bannatyne.

This post is part of a series about creating a PHP CMS. Click here to start from the beginning. Today, we will be using a form to get information and add it to the database.

Creating a Form
First, to get the information, we need to create a form. Our form will be in the new.php file. Paste the contents of new.txt into new.php. The action attribute of form tells us which page the user will go to when they click the submit button. The method attribute tells us how it is sent to the server. The value 'post' means that the information sent will not be shown in the URL. Another method is get, where the information is displayed in the URL. We will be using get later.

Form Validation
After the user submits the form, something has to be done with the information they sent. We will be using a variable called $_POST. For example, if a user submits a form, and in that form there is a field called 'userInput', and they entered 'hello, world', $_POST['userInput'] would contain 'hello, world'. In create.php, insert your PHP start tag and include functions.php. You will need to include it as '../functions.php' because create.php is in the admin directory. '../' means the parent directory. First, we will establish a database connection using connect();. And then we will check that the form fields are filled in, using an if statement.
if ($_POST['title']) { }

This checks if $_POST['title'] is true. If the 'title' field wasn't filled in, $_POST['title'] would be an empty string, meaning that it is false. If the title is entered, we will store it in a variable called $title. However, we aren't just going to use
$title = $_GET['title'];

Instead, we will use mysql_real_escape_string. This 'escapes' potentially harmful characters by adding a backslash in front of them so that the form input doesn't cause any problems. We will be using this with all user input.
if ($_POST['title']) { $title = mysql_real_escape_string($_POST['title']); }

We still need to do something if $_POST['title'] is not true, by using else. We will show an error message telling them to fill in the title field. You should have something like this now.
// Check if the title is entered if ($_POST['title']) { $title = mysql_real_escape_string($_POST['title']); } else { echo '<p>The title field is empty.</p>'; }

Now we can do the same thing with the body text.


// Check if the body is entered if ($_POST['body']) { $body = mysql_real_escape_string($_POST['body']); } else { echo '<p>The body field is empty.</p>'; }

We can get the date using time.


$date = time();

Now, before we insert values into the database, we will check that the title and body fields are filled by using an if statement with the && operator. && means 'and', so the expression for the if statement will only be true if both values are true.
if ($title && $body) { }

The method that we will use to execute MySQL queries is with mysql_query. There are other methods to execute queries, but I won't discuss them in this series.
mysql_query("INSERT INTO pages (title, body, date) VALUES ('$title', '$body', '$date')");

Let's take a look at the SQL query. INSERT INTO pages means that we will be adding a row to a table called pages. (title, body, date) means that we will be working with the fields title, body and date. VALUES ('$title', '$body', '$date') means that the values we are inserting will be using these variables. The values you are inserting must be in the same order as the list of fields to work with. You may notice that I used double quotes here, but in all of the other strings I used single quotes. This is because with double quotes, variables can be placed in strings, but they cannot with single quotes. Also, I prefer to use single quotes in SQL queries. After the if statement, we will use else to show a link back to new.php if either of the fields is not filled.
// If the title and body are both entered, insert into the database if ($title && $body) { connect(); mysql_query("INSERT INTO pages (title, body, date) VALUES ('$title', '$body', '$date')"); } else { echo '<p><a href="new.php">Back</a></p>'; }

Now to test that everything is working correctly, point your browser to admin/new.php and enter some test information. If everything works fine, you should see a blank page. If you got an error message, check your code to see if you made any mistakes. Areas to check would be functions.php, new.php and create.php. If you get a blank page, check your database viewer to see if any new rows have been added. If you see a new row, then you're done with this part of the series!

Creating a PHP CMS Part 4


August 17, 2009, in PHP,Programming,Web Design, by Eric Bannatyne. This post is part of a series about creating a PHP CMS. Click here to start from the beginning. Today we are going to be getting the page from the database and displaying it to the user. We will also set a home page for when a specific page is not requested. If you haven't already, create a few pages using the form we created in Part 3, and check the pages table in your database viewer to make sure everything is working correctly. After you've created a few pages, let's get into our database viewer to execute some SQL queries. In your pages table, choose one of your posts to use as a home page, and remember its id. On your database, execute this query.
INSERT INTO settings (name, VALUE) VALUES ('homePage', 'id');

Be sure you replace id with the page ID you chose. Now execute this query on the database.
INSERT INTO settings (name, VALUE) VALUES ('homeTitle', 'title');

Replace title with what you want to be displayed in the title bar on the home page. It should be something like the name of your site.

Displaying Information
Now that we've set information for the home page, we can get into some PHP. We will start by creating some more functions in functions.php. Today we will be creating four new functions called title, pageTitle, pageBody and pageDate. Title Bar With our title function, we will be displaying the title bar text. We will be using $_GET today. $_GET is similar to $_POST, except with $_GET, the information is displayed in the URL. For example, in 'index.php?id=23', there would be a variable called $_GET['id'] with a value of 23. Insert this code into the title function.
if ($_GET['id']) { } else { }

If an ID is specified, display the title of the page with that ID. If none is specified, then get the value of the homeTitle setting and display that. Inside the if block, we will put the value of $_GET['id'] in a variable called $pageID. We will convert it to an integer because that was type that the id field in our table was.
$pageID = (int) $_GET['id'];

Now, we will use another mysql query using mysql_query. This time, we will be using it in a variable called $result. This is because we will be using it to create an array from the mysql query.
$result = mysql_query("SELECT title FROM pages WHERE id='$pageID'");

SELECT title FROM pages means that we will get the value of the 'title' field from the 'pages' database. WHERE id='$pageID' means that we will only select a row where the 'id' field has this value (In this case it's the value we put in $pageID).
$row = mysql_fetch_array($result);

This uses mysql_fetch_array to take our MySQL query and turn the result into an array, and then stick that array in $row.
echo $row['title'];

This just displays the value of the key called 'title'. The key is the same as the field we used in our MySQL query. Inside the else section, insert this code.
$result = mysql_query("SELECT value FROM settings WHERE name='homeTitle'"); $row = mysql_fetch_array($result); echo $row['value'];

This pretty much does the same thing as what we just did, except it uses the value that we set as the home page title on the settings table. Page Title Paste the code inside of the title function into the pageTitle function. Inside the else section, replace 'homeTitle' in the MySQL query with 'homePage', and delete the line containing
echo $row['value'];

and add in
$pageID = $row['value']; $result = mysql_query("SELECT title FROM pages WHERE id='$pageID'"); $row = mysql_fetch_array($result); echo $row['title'];

This code will first get the home page ID specified in the 'settings' table and use that ID to get a title from the 'pages' table. Page Body and Page Date In the pageBody function, paste in the content of the pageTitle function, replacing all instances of 'title' with 'body'. Do the same with pageDate, this time replacing 'title' with 'date'. However, there is an extra step with pageDate. Delete the echo statements, and replace them with
$date = date('M d, Y', $row['date']);

Remember how we stored dates as Unix time? This converts it to a human-readable date and sticks it into a variable called $date. Now we can just echo $date to display the date the page was published. Using These Functions Now that we've created the functions, we can start using them in index.php. Open up index.php in

your text editor, and add in a basic HTML page structure. At the top of the file, add a PHP block. Inside this PHP block, include functions.php and connect to the database. Now add this between the title tags.
<?php title(); ?>

Now you can use <?php pageTitle(); ?>, <?php pageBody(); ?> and <?php pageDate(); ?> to display the page. Open index.php in your browser and, if everything went correctly, you should see the page you set as the home page. Try adding ?id=page (replace 'page' with the ID of one of your posts) to see a different page. In the next post in this series, we will be displaying a list of posts, for a navigation list and for an administration panel.

Creating a PHP CMS Part 5


August 19, 2009, in PHP,Programming,Web Design, by Eric Bannatyne. This post is part of a series about creating a PHP CMS. Click here to start from the beginning. In the last few posts, we learned how to display information from the database. Today, we will be creating lists of posts for a navigation list, and for the CMS admin.

Navigation List
In functions.php, create a new function called listPages. The first thing we will do is make sure that the page set as the home page is listed first.
$result = mysql_query("SELECT value FROM settings WHERE name='homePage'"); $row = mysql_fetch_array($result); $homeID = $row['value']; $result = mysql_query("SELECT title FROM pages WHERE id='$homeID'"); $row = mysql_fetch_array($result); $homeTitle = $row['title']; echo "<li><a href='" . BASE_URL . "/index.php'>$homeTitle</a></li>";

Here we are using our BASE_URL constant in the echo statement. This is to prepend our base url to the filename 'index.php'. Next we will list the rest of the pages.
$result = mysql_query("SELECT id, title FROM pages"); while ($row = mysql_fetch_array($result)) { // Do not list the home page twice if ($row['id'] != $homeID) { $pageID = $row['id']; $pageTitle = $row['title']; echo "<li><a href='" . BASE_URL . "/index.php? id=$pageID'>$pageTitle</a></li>"; }

while is a type of loop. In this case, we are displaying a list item while there is still a row to display. Our if statement in the loop makes sure that the home page will not be listed twice. Save functions.php, and in index.php, call our listPages function, wrapping it in <ul> (or <ol>) tags. You should see a list of the pages you created, with links.

Administration Table
In the administration panel, we will be listing pages again, but this time in a table with more information. This will include the page title with a link to the page, the page ID, links to delete, edit and set a home page, and a note saying which is the home page.
function displayAdmin() { 1 // Find the home page ID 2 $result = mysql_query("SELECT value FROM settings WHERE 3 name='homePage'"); 4 $row = mysql_fetch_array($result); 5 6 $homeID = $row['value']; 7 8 // Display a table 9 $result = mysql_query("SELECT id, title, date FROM pages"); 10 11 echo '<table>'; 12 echo '<tr> 13 <th>ID</th> 14 <th>Title</th> 15 <th>Date</th> 16 <th>Actions</th> 17 </tr>'; 18 19 while ($row = mysql_fetch_array($result)) { 20 $id = $row['id']; 21 $title = $row['title']; 22 $date = date('M d, Y', $row['date']); 23 24 echo "<tr> 25 <td>$id</td> 26 <td><a href='". BASE_URL . "/index.php?id=$id'>$title</a>"; 27 if ($id == $homeID) { 28 echo ' <strong>(Home Page)</strong>'; 29 } 30 echo "</td> 31 <td>$date</td> 32 <td><a href='edit.php?id=$id'>Edit</a><br /> 33 <a href='confirm.php?id=$id'>Delete</a><br /> 34 <a href='sethome.php?id=$id'>Set as Home</a>"; 35 } 36 echo '</table>'; 37 }

This is basically just what we were doing before, except displaying more information. Now in admin/index.php, include functions.php (don't forget the '../'.), and call the displayAdmin function. Make sure that everything is correct, and take a break for the day.

Creating a PHP CMS Part 6


August 21, 2009, in PHP,Programming,Web Design, by Eric Bannatyne. This post is part of a series about creating a PHP CMS. Click here to start from the beginning. In today's post, I will be showing you how to create administration functions for editing and deleting posts, and setting a new default home page. First, inside the 'admin' directory, create these files:

edit.php update.php confirm.php delete.php sethome.php

edit.php will have a form for making changes to a page, and update.php will do the actual work with the database. confirm.php will just be a page to confirm that you want to delete a file, and delete.php will delete the file. sethome.php will be used to change the home page.

Updating Pages
First, paste the contents of new.php into edit.php. In edit.php, call the connect() function right after including function.php, and add the following code after the </p> closing tag for the 'body' field.
<p> <label for="date">Change the date?</label> <input type="checkbox" name="date" value="1" /> </p>

This adds a checkbox asking if you would like to change the post's date to today's date. Now, between the textarea tags for the body text, add in this code.
<?php echo $body; ?>

So that you don't have to add in from memory parts of the page that you do not want to change. Finally, change value of the the action attribute of the form element to
update.php?id=<?php echo $id; ?>

Now enter the following code in update.php


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <?php // Update database tables require_once '../config.php'; require_once '../functions.php'; connect(); // Get the page id $id = $_GET['id']; // Check if the title is entered if ($_POST['title']) { $title = mysql_real_escape_string($_POST['title']);

} else { echo '<p>The title is empty.</p>'; 16 } 17 18 19 // Check if the body is entered 20 if ($_POST['body']) { $body = mysql_real_escape_string($_POST['body']); 21 22 } else { echo '<p>The body is empty.</p>'; 23 24 } 25 26 // If the title and body are both entered, insert into the database 27 if ($title && $body) { 28 // Check if they want to change the date 29 if (isset($_POST['date'])) { 30 // Get Unix time 31 $date = mysql_real_escape_string(time()); 32 33 mysql_query("UPDATE pages SET title='$title', body='$body', date='$date' WHERE 34 id='$id'"); 35 } else { 36 mysql_query("UPDATE pages SET title='$title', body='$body' WHERE id='$id'"); 37 } 38 } else { 39 echo '<p><a href="edit.php">Back</a></p>'; 40 } 41 ?>

This basically does the same thing as when we were inserting posts, except this time we are using UPDATE to modify existing records in the database. You might also see that we are using if (isset($_POST['date'])) to check if the 'change the date' checkbox is checked. If it is, we set a new date.

Deleting Pages
Our confirm.php file will be extremely simple, with just some links to confirm deletion of the page. We are focusing entirely on functionality, and you can easily style this page (and all of the other pages) after functionality is complete. After all, who wants a site that looks good, but does absolutely nothing?
<p>Are you sure?</p> <ul> <li><a href="<?php echo $_POST['id']; ?>">Yes</a></li> <li><a href="index.php">No</a></li> </ul>

Just add in that code into a page with your styling in place. I was originally just going to use p tags, but I'm pretty sure that that wouldn't be semantic enough. Now we can get to the actual 'action' with delete.php! There actually isn't that much 'action' going on, though, with just 6 lines of code. (Plus 5 lines of whitespace, and 2 lines of comments)
1 2 3 4 5 6 7 <?php // Delete records require_once '../functions.php'; connect();

8 9 10 11 12 13

// Get page id $id = $_GET['id']; mysql_query("DELETE FROM pages WHERE id='$id'"); ?>

This simply includes functions.php, connects to the database, stores the page ID in a variable, and runs a MySQL query using DELETE FROM. This just deletes a record from a database table. Be sure that you don't forget to include WHERE, because if you don't that will empty your entire table! Trust me, this has happened to me before. Now you should be able to get to edit.php and confirm.php from our admin table in part 5. Test everything out to make sure it's working properly.

Setting the Home Page


Remember, we also added a link to set a specific page as the home page in our admin table. To do this, simply paste the contents of delete.php into sethome.php. Don't worry, we won't be deleting our home page. Delete everything in between parentheses on the line with mysql_query and replace it with
"UPDATE settings SET value='$id' WHERE name='homePage'"

This simply updates the value of the 'homePage' setting to match the ID of the page you chose. That's it for this part of the series, be sure to subscribe to the RSS Feed for updates. In the next post in this series, I will talk about restricting access to the admin area using usernames and passwords.

Creating a PHP CMS Part 7


August 24, 2009, in PHP,Programming,Web Design, by Eric Bannatyne. This post is part of a series about creating a PHP CMS. Click here to start from the beginning. Today we will be creating a very simple login system used to restrict access to the administration panel. Site security is such a large topic, I could write an entire series on security alone. We will be creating a login form to check if a user exists, and if the user does exist, it logs them in. We will not be creating a registration form, or a forgotten password form. I may cover these topics in another blog post. If you would just like to download the finished source code, you can Click here to get it.

Creating a User
The first thing we will be doing is creating a user. To create a user, we first need a database table for storing users. Run the following SQL on your database.
CREATE TABLE users ( id INTEGER AUTO_INCREMENT, username VARCHAR(30), password VARCHAR(41), PRIMARY KEY (id) );

This creates a table for storing users, with an ID, username and password. The username can be up

to 30 characters long. The password needs to be quite long, because we will be encrypting our passwords. If you are storing passwords, they should always be encrypted, instead of being stored in plain text. This is because if someone manages to get access to the database, they can see all of the passwords if they are stored in plain text. We will be encrypting our passwords using md5 for now, but after I wrote the login system, I read that sha1 is more secure. I will be using md5 in this tutorial, but easily apply the same ideas to sha1 encryption. Now we can create a user, using some SQL. I will call the user 'admin', and the password will be 'password'. Using this md5 Hash Generator, the md5 version of the word 'password' is
5f4dcc3b5aa765d61d8327deb882cf99

Now we will create a MySQL query to insert the user into the database.
INSERT INTO users (username, password) VALUES ( 'admin', 'password' );

Be sure to replace 'password' with the md5 hash of your password.

The Login Form


Create a new file in the admin directory called login.php. Paste in the following code.
<form method="post" action=""> <p> <label for="name">Username: </label> <input type="text" name="username" /> </p> <p> <label for="password">Password: </label> <input type="password" name="password" /> </p> <p> <input type="submit" id="submit" value="Login" name="submit" /> </p> </form>

This is just a simple login form. The 'password' field is using the type of password so that any input is hidden. You can also see that the action attribute of the form is empty. This is because we will be validating the user on the same page.

The Login Functions


In functions.php, we will be creating a few new functions. The first one we will create is called verifyUser. In between the parentheses, add two variables, called $name and $pass. These are the arguments we will accept when calling this function. Inside the function, insert the following code.
// Escape strings $username = mysql_real_escape_string($name); $password = mysql_real_escape_string($pass); $result = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password' LIMIT 1");

if (mysql_fetch_array($result)) { return true; } else { return false; }

First, we escape the strings. This is important because any user can get to the login form, not just administrators. Next, we select the row from the 'users' table where both the username and password given are the same as those in the database. LIMIT 1 makes sure that only one row is returned. Next, we have an if statement. The condition is mysql_fetch_array($result). This means that if there were rows to create an array, the condition is true. If no rows were returned, it returns false. Inside the conditional block, we have return true. This means that when we call this function, if the user exists, we get 'true'. If not, we get 'false'. The next function we will create is called validateUser. Add the variables $name and $pass in between the parentheses again. Inside the function, enter this code.
$check = verifyUser($name, md5($pass)); if ($check) { $_SESSION['status'] = 'authorized'; header('location: index.php'); } else { return 'Please enter a correct username and password'; }

This stores the result of verifyUser in the $check variable. The arguments used are the username and an md5 hashed version of the password. For example, if the user is verified correctly, $check will have a value of 'true'. Next we have an if statement. The condition is $check, so it will continue if verifyUser returned 'true'. We have a new variable called $_SESSIONS. This is an array used for storing session information. We are using a session called 'status', and giving it a value of 'authorized'. Next, we call the header function. The argument is 'location: index.php'. This redirects the user to the file 'index.php' when the user has been verified. In our else block, we simply return a helpful error message. For the next step, go to login.php and add a PHP block at the top of the file. First, include functions.php and call the connect function. After connecting to the database, call a function called session_start(). This initializes our session data. Next, add in this code.
if ($_POST['username'] && $_POST['password']) { $result = validateUser($_POST['username'], $_POST['password']); }

This checks if the user has submitted the form by checking if $_POST['username'] and $_POST['password'] are true. Next we call the validateUser function. Now go to login.php in your browser and enter the login information that you set. If everything went fine, you should be redirected to index.php. Now try entering incorrect login credentials. You should be back at login.php. Now we need a function to log the user out. In functions.php, create a new function called logout. Paste in this code inside the function.

if (isset($_SESSION['status'])) { unset($_SESSION['status']); // Remove the cookie if (isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time() - 1000); session_destroy(); }

if (isset($_SESSION['status'])) checks if the user is logged in. If they are, then unset the $_SESSION['status'] variable. Next, we check if a cookie exists with the name of the current session. If the cookie exists, we remove it using setcookie. To remove a cookie, we set an expiration date before the current time. In this case, we set it to 1000 seconds earlier. Next, we use session_destroy(), which destroys our session data. Now add the following code in login.php, inside the PHP block.
if ($_GET['status'] == 'logout') { logout(); }

This checks if the URL contains 'status=logout', and if it is, it calls the logout function. In index.php, add a link to 'login.php?status=logout'. Now try logging out and logging back in to make sure everything works. However, we haven't restricted access to index.php. We will create a new function called checkMember to restrict access. This function will be very simple.
function checkMember() { session_start(); if($_SESSION['status'] != 'authorized') { header('location: login.php'); }

First we initialize the session data with session_start. Then, we check if $_SESSION['status'] is not equal to 'authorized', like we set in the validateUser function. This means that the user is not logged in. If they are not logged in, we redirect them to login.php. In all of the files in the admin directory, except for login.php, call the checkMember function after connecting to the database. Now make sure you are logged out, and try accessing the pages in the admin directory without logging in. If everything went well, you should be redirected to login.php. That's it for this series. If you've been following the series, you've learned how to connect to a database with PHP, create, read, update and delete pages, and how to secure pages of a site. I hope to write some blog posts expanding on these topics in the future. Click here to download the finished source code. I've added a few more things, such as a few messages, and a method of checking if a page exists. You can check out the source code to see how I did that. One thing that I did not discuss is styling. I've recently started trying out the CodeIgniter framework, and I am working on a simple themeing system for it in my spare time.

You might also like