Creating a Login Script for a PHP/MySQL Blogging System

In this three-part tutorial we are going to be creating an open blogging system. We are also going to provide scripts that will make it possible to switch to a closed blogging system. This article, which is the first part, will cover the creation of the login scripts for a closed system.


The file for the login script can be downloaded here.
  • An open blogging system is a system that allows anyone to contribute to a blog without having to register. In many cases, it also allows any user to start a new topic that will then have its own replies,  as opposed to just commenting on a topic that the blog owner started. This kind of blog is suitable for people who have just created a website and do not have a lot of web traffic.
  • A closed blogging system is one that requires registration and allows most users to contribute to a topic instead of creating their own. This kind of blog is suitable for people that have a lot of traffic on their websites.

In the first part of this article, we will create a login script for those of you who prefer a closed blogging system. You can skip this part if you wish and come back next week to check out the next part in this series, which will deal with creating a blog if you are not interested in a closed system. The login script will have a MYSQL table which it will reference to verify the existence of a user at login. It will also have various scripts that will help register a new user and retrieve forgotten passwords.

Login Script

The login script will have the following pages:

  • Login.php – Enables users to log in.
  • Logout.php – Enables logging out.
  • Register.php – Creates new users.
  • Password.php – Password recovery.
  • Messages.php – Handles error messages.

Let’s create a table that will gather the following information about a user:

  • Username
  • Password>
  • Level
    •  Admin – This will be the moderator of the system
    •  Normal – Normal access rights
  •  Date_joined
  • IP Address – Enables us to identify and ban users.
  • Email – Used for password recovery.
  • Isbanned – Enable us to ban users

Here’s the table:

CREATE TABLE `user` (
  `id` int(5) NOT NULL auto_increment,
  `uname` varchar(98) NOT NULL default ”,
  `pw` varchar(98) NOT NULL default ”,
  `email` varchar(100) NOT NULL default ”,
  `date_joined` datetime NOT NULL default ’0000-00-00 00:00:00′,
  `ip` varchar(20) NOT NULL default ”,
  `level` varchar(10) NOT NULL default ”,
  `isbanned` enum(‘yes’,'no’) NOT NULL default ‘no’,
  PRIMARY KEY  (`id`)
) TYPE=MyISAM AUTO_INCREMENT=11 ;

As you can see from the table layout, the table gathers a lot of information about a user. The most significant item of them all is the “isbanned” field. This field is responsible for checking whether or not a user is banned. The “ip” field stores the IP address of the user, which will be used to reinforce the isbanned status of a user.

Simply copy and paste the code into your PHP admin and run the SQL.

{mospagebreak title=Login.php}

This file displays a form that requests your username and password and also gives you the options to register as a new user or recover your password if you’ve forgotten it.

 Once you’ve  pressed the submit button the following code gets executed:

<?
session_start();
if(isset($_GET['reg'])){
$reg=$_GET['reg'];
}else{
$reg=”";
}
if($reg==1){
$msg1=”<font color=”#FF0000″><b>Your details have been added,
please login</b></font>”;
}elseif($reg==2){
$msg1=”<font color=”#FF0000″><b>You have been successfully
logged out.</b></font>”;
}elseif($reg==3){
$msg1=”<font color=”#FF0000″><b>You have been redirected because you need to be logged on as administrator.</b></font>”;
}
if(isset($_POST['submit'])){
if( empty($_POST['uname']) && (empty($_POST['upass']))){
header( “Location:Messages.php?msg=1″ );
exit();
}
//transfer to shorter var
$n=$_POST['uname'];
$p=$_POST['upass'];
//connect to db
include(‘config.php’);
$query=”select * from user where uname=’$n’ and pw=’$p’”;
if($result=mysql_query($query)){
$row=mysql_fetch_assoc($result);
//check each var
if($n !=$row['uname']){
header( “Location:Messages.php?msg=2″ );
exit();
}
if($p !=$row['pw']){
header( “Location:Messages.php?msg=11″ );
exit();
}
if($row['isbanned']==’yes’){
header( “Location:Messages.php?msg=12″ );
exit();
}
}//ifresult
//put in session vars
$_SESSION['level'] = $row['level'];
$_SESSION['status'] = ‘logged’;
$_SESSION['username'] = $n;
//This takes you to the admin pages; change this to take you to
wherever you want it //to go.
header(“location:../admin/main.php”);
exit;
}?>

Ignore the first part that falls under “if(isset($_GET['reg'])){}” since it concerns another script; we will come to it later. The next part does the following things:

  • Checks to see whether a user exists. If so, the username and password is compared with the information in the database. It also checks to see whether the user is banned. If all the checks are okay, the script puts the username in a session variable and then sends the user through to the blog.
  • If the user does not exist, the program goes to the messages page and displays an error message.

The script also checks the user’s banned status. If a user is banned, then the script directs you to the Messages page. The submitted username and password is checked individually and then the appropriate action is taken. This enables the user to know exactly which of the two, username or password, is wrong.

You will also notice that some session variables are created. These are going to be used by the blog system to identify the user and by the admin script to identify whether a user indeed has admin level clearance.

{mospagebreak title=Logout.php}

Logs a user out with the following code:

<?
session_start();
if($_SESSION["status"]=”logged”) {
session_unset();
session_destroy();
header( “Location:login.php?reg=2″ );
exit();
}
else{
if ($_SESSION["status"]=”not logged”) {
//the session variable isn’t registered, the user shouldn’t even
be on this page
header( “Location:login.php” );
exit();
}
}
?>

 

The ‘header( “Location:login.php?reg=2″ ); ‘ code sends a reg value of 2 to the login.php page, which informs the user that he/she has been logged out. To log out a user, we simply empty the session variables that have been filled at login. This is done by the session_unset() and session_destroy() functions.

Register.php

This script registers or adds a new user.

Example output of the register.php

The following code does the job:

<?
if(isset($_POST['Submit'])){
//NEED TO CHECK IF FIELDS ARE FILLED IN
if( empty($_POST['name']) && (empty($_POST['email']))){
header(“Location:Messages.php?msg=3″);
exit();
}
if( empty($_POST['pw1']) && (empty($_POST['pw2']))){
header( “Location:Messages.php?msg=4″ );
exit();
}
$name=$_POST['name'];
$email=$_POST['email'];
$pw1=$_POST['pw1'];
$pw2=$_POST['pw2'];
if(“$pw1″ !== “$pw2″  ){
header( “Location:Messages.php?msg=5″ );
exit();
}
$ip = $_SERVER['REMOTE_ADDR'];
if(empty($ip)){
header(“location:Messages.php?msg=13″);
exit();
}
if(isset($_POST['select'])){
$level=$_POST['select'];
}else{
$level=”Normal”;
}
//connect to the db server , check if uname exist
include(‘config.php’);
$query=(“Select * from user where uname=’$name’”);
$result= mysql_query($query);
$num=mysql_num_rows($result);
if ($num > 0) {//Username already exist
header( “Location:Messages.php?msg=6″ );
exit();
}else{
//if username does not exist insert user details
$query=( “INSERT INTO user (uname, pw,email,date_joined,ip,level,isbanned) VALUES (‘$name’,password
(‘$pw1′),’$email’,NOW(),’$ip’,'$level’,'no’)”);
if(!@mysql_query ($query)) {
echo mysql_error();
}else{
if(empty($_POST['select'])){
header(“location:login.php?reg=1″);
exit;
}else{
header(“location:../admin/main.php”);
exit;
}
}
}
mysql_close();
}?>

The script does three things:

  • Checks whether all the fields are filled in.  If not, the program goes to the messages page where the appropriate error is displayed.
  • Checks whether the username already exists. If so, the program goes to the messages page where the appropriate error is displayed.
  • If the username does not exist, the script adds the user details and goes straight to the login page. Where the user can now login.

Because this login system is designed for a closed blogging system, it is very important that we have the IP address of a user. For this reason I’ve  included the following code:

$ip = $_SERVER['REMOTE_ADDR'];
if(empty($ip)){
header(“location:Messages.php?msg=13″);
exit();
}

This code checks to see whether the users’ IP address is empty. If so, it simply sends the user to the messages page. This will stop anyone who does not have an IP address from registering. You can of course remove this piece of code if your security needs are limited.

{mospagebreak title=Password.php}

This script sends the password that the user has forgotten to his/her email address.

Example output of the password script.

Here’s the password code:

<?
include(“fns.php”);
include “config.php”;
if(isset($_POST['Submit'])){
//1. Check if form fields are filled in
if(!filledin($_POST)){
header( “Location:Messages.php?msg=7″ );
exit();
}
$name=$_POST['name'];
$em=$_POST['mail'];
//2. Check if entered name exist
$query=”Select pw from user where uname=’$name’” or die(mysql_error());
$result= mysql_query($query);
if(mysql_num_rows($result)>0){
for ($i=0; $i<mysql_num_rows($result); $i++) {
$row = mysql_fetch_assoc($result);
$pass=$row['pw'];
$to=”$emrn”;
$from=”From: Admin@jacquesnoah.co.ukrn”;
$msg=”Password:$passrn”;
$msg .=”Username:$namern”;
$msg .=”Please change your password as soon as you logonrn”;
$subject=”From Admin re:Your Login Passwordrn”;
}
}else{
header( “Location:Messages.php?msg=8″ );
exit();
}
//3. Send password to user
if(mail($to,$subject,$msg,$from)){
header( “Location:Messages.php?msg=9&email=<?php echo $em; ?>” );
exit();
//echo “Please click here to log”;
}else{
header( “Location:Messages.php?msg=10″);
exit();
}
}
?>

This code does three things:

  • Checks to see if all fields are filled in. Notice the use of the function called ‘filledin()’ in the line “if(!filledin($_POST)){}“>. That function is declared in the functions script called “fns.php” which is included in at the top of the code. It just checks whether all posted variables contain something.
  • Checks to see if entered name exists. This provides us with extra security, by checking whether the username and email address exist.
  • Once all security checks have been passed, it sends the password.

Conclusion

These are all the pages that we need to run a effective login script. It can of course always be improved, but for now it is adequate, security wise, for a low security application such as a web log. Don’t forget to change the contents of the config.php script. Next week we will create the actual blog.

Google+ Comments

Google+ Comments