Sponsored by NuSphere - PHP Software for PHP Application Developers - On Sale This Week for $100 off


PHP Tutorials and Scripts   




Title: Creating a login system    Marked Cool    (Review this resource)
Author: econner
Posted On: 2004-11-17
Category: Home > PHP Tutorials

Popularity: 5 points out of 10    

Description: Creating a registration/login system with php/mysql.

Total Hits: 8534     Total Votes: 0     Total Points: 0 (0 reviews)        [ Download ]   

Page Navigation:  [1]


Creating a login system with php and smarty

This tutorial will show you how to create a login system including registrations and logins. It will make use of a smarty template system. If you have not used smarty, read my tutorial on it here.

First create a users table similar to the following. (I recommend prefixing all your tables with a certain acronym, word etc. but in this tutorial we won't)

CREATE TABLE users (
id INT NOT NULL AUTO_INCREMENT
username varchar(28);
password varchar(40); // we'll be encrypting the password
);

This is the bare minimum of what you'll need, you could and probably would add more fields to this table. Next we'll create our registration form. Create a new html file for smarty like this:

html:
<html>
<
head>
<
title></title>
</
head>
<
body>
{if
$error != ""}{$error}{/if}
{if
$success == 1}Account successfully created! Click <a href="login.php">here</a> to login.{/if}
<
form action="{$smarty.server.PHP_SELF}" method="post">
Username: <input type="text" name="username">
Password: <input type="password" name="password">
Confirm: <input type="password" name="confirm">
</
form>
</
body>
</
html>


The if statements are used to display output from our script. Ok now we'll create a php file to validate this form and if all the info is inputted the way we want we will insert a new row into the database for that user.

php:


<?php
# register.php

require_once ("./templates/libs.inc.php"); // include the smarty file

if(
$_POST)
{

    // Initialize some variables for storing errors or the success of the registration.

    $error
= '';
    
$success = 0;

    // Make sure the user filled in all of the fields
    if(
$_POST['username'] == '' || $_POST['password'] == '')
    {
        
$error .= "<li>A required field was not filled in.</li>";
    }
    
    // Make sure the passwords are eqaul.
    if(
$_POST['password'] != $_POST['confirm'])
    {
        
$error .= "<li>Passwords did not match.</li>";
    }
    
    // Make sure the username has not already been signed up with.
    
$sql = "SELECT username FROM users";
    
$result = mysql_query($sql) or die(mysql_error());
    while(
$row = mysql_fetch_assoc($result))
    {
        if(
$row['username'] == $_POST['username'])
        {
            
$error .= "<li>That username is take, please try another.</li>";
        }
    }
    

    if(
$error != '')
    {
// If there is no error insert the new registration into the database
        
$password = sha1($_POST['password']); // Encrypt the password
        
$username = $_POST['username'];
        
$sql = "INSERT INTO users(username, password) VALUES('$username', '$password')";
        
mysql_query($sql) or die(mysql_error());
        
$success = 1;
    }
}

// Assign the success/failure variables to smarty.
$smarty->assign("error", $error);
$smarty->assign("success", $success);

// Display the file.
$smarty->display("register.tpl");
?>


Ok our registration script is complete. A user should now be able to register, inserting a new row into the users table. Next we'll create a functions file which will hold a function to make sure a user is logged in and if not it will forward them to the login page. This file should be included on every page you want to be secure.

php:
# functions.php

/*
* Our secure function, this will check to make sure a certain session variable (id) is set
* and if not it will forward the user to a login page where they can login.
*/
function secure()
{
  if(!(
$_SESSION['id']) || ($_SESSION['id'] == ""))
  {
    
Header("Location: ./login.php");
    exit();
  }
}


This functions.php should be included on all the pages you want to have private. The basic functionality behind it is to just check the session variable that will be set when a user logs in. Next we'll want a login page to of course :) log a user in and to check their username/password:

php:

# login.php
/*
* First we want a function that will check and make sure the inputted username is valid.
*/
function check($form)
{
    
$error = "";
    
$username = $form['username'];  //get the users inputted username
    
$password = $form['password'];  //get the users inputted password
  
    
if(trim($username) == "") $error .= "<li>Your forgot to enter a username.</li>";
    if(
trim($password) == "") $error .= "<li>Your forgot to enter a password.</li>";
  
    
/*
    * Do a database query and make sure their username/password is correct.
    */
    
$sql = "SELECT username,password FROM users WHERE username='$username' AND password='$password'";
    
$result = mysql_query($sql) or die(mysql_error());
    
$num = mysql_num_rows($result);
  
    if(
$num)
    {
        return
TRUE;
    }
    else
    {
        
$error .= "<li>Wrong username/password.</li>";
        return
$error;
    }
}

/*
* Next we need a function to login the user and put their id into a variable
* so we can validate it and use it on other pages.
*/
function login($form)
{
  
$username = $form['username'];
  
$password = $form['password'];
  
  
$sql = "SELECT id FROM users WHERE username='$username' AND password='$password'";
  
$result = mysql_query($sql) or die(mysql_error());
  
$id = mysql_fetch_assoc($result);

   // the main reason for using the users id is that usually you will want to do more database queries on pages after this using that id so it is helpful to just set it now.
  return
$id['id'];
}

if(
$_POST)
{
    
// check the users input with the function
    
$error = check($_POST);
    
    if(
trim($error) === TRUE)
    {
        
$_SESSION['id'] = login($_POST);
        
Header("Location: ./index.php"); // Redirect correct input to a secure page
        
exit();
      }
}

$smarty->assign("error", $error);
$smarty->display("login.tpl");
?>


Ok we've now created our login page. The only thing left to do is create a login form which will be the login.tpl file.

php:
<html>
<
head>
<
title></title>
</
head>
<
body>
{if
$error != ""}Error:{$error}{/if}
<
form action="{$smarty.server.PHP_SELF}" method="post">
Username: <input type="text" name="username">
Password: <input type="password" name="password">
</
form>
</
body>
</
html>



Thats it! We're finished. You should now have a working login script.


Page Navigation:  [1]



© Copyright 2003-2008 www.php-editors.com. The ultimate PHP Editor and PHP IDE site.