Wednesday, June 9, 2010

How to create a login page?

Login script tutorial, sample code

The entry point of any e-commerce website, membership portals and any login based web applications is a login page with user name and password. This is required for websites offering paid products/digital content/services/music and video content. Here is the tutorial for creating a login page using PHP and MySql database.

This tutorial assumes you have basic understanding of PHP and MySql. A membership login requires a registration page, a database table to store member / user details. A login page and script to validate login. The registration page will store member/user data in MySql database table. So first we need to create a table. I have provided the sql script below.

CREATE TABLE `members` (
  `ID` int(11) NOT NULL auto_increment,
  `Username` varchar(255) NOT NULL,
  `Password` varchar(255) NOT NULL,
  PRIMARY KEY  (`ID`),
  UNIQUE KEY `Username` (`Username`)
) ENGINE=MyISAM;

I have used the minimum number of fields to make it simple. We can write a complicated script that will send a verification email to user. Upon the user clicking activate link, his account will be activated. This is a complex script and will require more fields in the table. I will explain in future.

You save the script in a text file and execute it MySql command Window. For example, if you save the script as c:\db.sql in my sql command prompt type \. c:\db.sql This will execute whatever sql code in the file.

After the table is created create a registration page. Name it register.php. Write the following code.
//******* start of register.php
$DB_Server="localhost"; //database server
$DB_User="root"; ///mysql username
$DB_Password=""; //set mysql password
$DB_Database="test"; //database name
if ($_POST)
{
$user=trim($_POST['username']);
$passwd=trim($_POST['password']);
$email=trim($_POST['email']);

if ($user=="" | $passwd=="")
{   
    echo 'Please provide valid user name and password! Thank you';   
    exit();
}

$link = mysql_connect($DB_Server, $DB_User, $DB_Password);
if (!$link) {
    die('Not connected : ' . mysql_error());
}

// make foo the current db
$db_selected = mysql_select_db($DB_Database, $link);
if (!$db_selected) {
    die ('Error: ' . mysql_error());
}

//Create INSERT query
    $qry = "INSERT INTO members(username, password, email) VALUES('$user','$passwd','$email')";
    echo $qry;
    $result = mysql_query($qry);
    //Check whether the query was successful or not
    if($result)
    {

    echo 'You have been registered successfully. Please Login';

    }
    else
    {
        echo 'Error: ' . mysql_error();
        echo '
Registration failed. Try again';
    }

exit();
}
?>





User Name
Password
//**** End of register.php
The above file will check whether it is post back (by user submitting the form using submit button) using if ($_POST). It will return true if post back. otherwise it will display a form for user entering registration data like user name and password. If post back it will open MySql using mysql_connect() function. The parameters for this function are Servername, userid, password. You have to set these variable at the beginning of the file. The next function mysql_select_db() will select the current database to use. $result = mysql_query($qry); will execute the $qry and store the result set in $result. By checking this true or false we can be sure whether the query was success or not. This is all about the simple registration. The script will check for simple validation of blank user name and blank password.

The next thing is the login page. I have put the code below. Explanation will follow.
//********* login.php

if ($_POST)
{
$DB_Server="localhost";
$DB_User="root";
$DB_Password="myuniverse";
$DB_Database="test";

$link = mysql_connect($DB_Server, $DB_User, $DB_Password);
if (!$link) {
    die('Not connected : ' . mysql_error());
}

// make foo the current db
$db_selected = mysql_select_db($DB_Database, $link);
if (!$db_selected) {
    die ('Error: ' . mysql_error());
}
$user=trim($_POST['username']);
$pass=trim($_POST['password']);

$result = mysql_query("SELECT id, username, password FROM members WHERE username='$user' AND password='$pass'");
if (!$result) {
    die ('Error: ' . mysql_error());
}
$num = mysql_num_rows($result);
if ( $num > 0 )
{
session_start();
$member = mysql_fetch_assoc($result);
$_SESSION['SES_member_id']=$member['id'];
$_SESSION['SES_member_name']=$member['username'];
echo 'Login success';
}
else
{

echo 'userid/password is invalid.try again';

}

exit();
}

?>

Login



User Name
Password


//********* End of login.phpWhen the form is submitted by the user by clicking submit button, the form variables will be posted back to the server. We verify it using if ($_POST). Then we will open connection to the database and check whether the given user name and password is available in the database table. If available we will create new session by calling session_start() function.


session_start() creates a session or resumes the current one based on the current session id that's being passed via a request, such as GET, POST, or a cookie. After calling session_start() session variables are available to us. We can store the user name in a session variable. Now the user is logged in to the server. Whenever we want to check user login status we check the session variable with isset() function.We stored the session variable by using $_SESSION['SES_member_name']=$member['username'];

We can check the status by isset($_SESSION['SES_member_name']). We can further enhance the script by using md5 hash for passwords. Storing plain passwords is a security vulnerability and should not be done. The function md5() Returns the hash as a 32-character hexadecimal number. Use this function before storing passwords in database. We can use email activation of accounts. This way we can verify the email of users. To avoid automatic registrations you can use captcha. recaptcha is free to use captcha that will require visual verification of alphanumeric characters. You can use this in your registration pages to avoid automated bulk registrations. You can use cookies to remember a user session. You can use Php SetCookie() function to store a cookie in user's computer browser. You can check for the presence of cookie and automatically log user in. If you have questions feel free to mail me: sundaracm@gmail.com

No comments:

Post a Comment