Friday, 26 June 2015

PHP: User Registration and Login Script with PHP and MySQL

In this tutorial we will discuss about how to create user registration and login management system with PHP and MySQL in simple procedural way. user registration and login system is most important thing for any kind of web applications and session plays important role in this type of system, for that we have to use session, In this tutorial, we are going to use PHP sessions to keep user login status., so how to do it let’s see in detail.

First of all create a database and table as below.
you can create it by importing following sql command in to your phpmyadmin.
database : dbtest
table : users
CREATE DATABASE `dbtest` ;
CREATE TABLE `dbtest`.`users` (
`user_id` INT( 5 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 25 ) NOT NULL ,
`email` VARCHAR( 35 ) NOT NULL ,
`password` VARCHAR( 50 ) NOT NULL ,
UNIQUE (`email`)
) ENGINE = MYISAM ;
copy-paste the above sql code into phpmyqdmin to create database and table.

Now we have to create following files..
–dbconnect.php
–register.php
–index.php
–home.php
–logout.php

dbconnect.php

contains code for localhost connection and database selection.
<?php
if(!mysql_connect("localhost","root",""))
{
     die('oops connection problem ! --> '.mysql_error());
}
if(!mysql_select_db("dbtest"))
{
     die('oops database selection problem ! --> '.mysql_error());
}
?>


NOTE : we should have start session in all the pages.
>> I have used here simple HTML5 required attribute to validate the following register and login forms.

register.php

contains simple html form and few lines of php code.
save this file as ‘register.php‘, this file contains simple html form with all the required registration fields except user id because it’s auto incremented and some php code for registering a new user. all the user registration process can be done in this single php file.
<?php
session_start();
if(isset($_SESSION['user'])!="")
{
 header("Location: home.php");
}
include_once 'dbconnect.php';

if(isset($_POST['btn-signup']))
{
 $uname = mysql_real_escape_string($_POST['uname']);
 $email = mysql_real_escape_string($_POST['email']);
 $upass = md5(mysql_real_escape_string($_POST['pass']));
 
 if(mysql_query("INSERT INTO users(username,email,password) VALUES('$uname','$email','$upass')"))
 {
  ?>
        <script>alert('successfully registered ');</script>
        <?php
 }
 else
 {
  ?>
        <script>alert('error while registering you...');</script>
        <?php
 }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login & Registration System</title>
<link rel="stylesheet" href="style.css" type="text/css" />

</head>
<body>
<center>
<div id="login-form">
<form method="post">
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="uname" placeholder="User Name" required /></td>
</tr>
<tr>
<td><input type="email" name="email" placeholder="Your Email" required /></td>
</tr>
<tr>
<td><input type="password" name="pass" placeholder="Your Password" required /></td>
</tr>
<tr>
<td><button type="submit" name="btn-signup">Sign Me Up</button></td>
</tr>
<tr>
<td><a href="index.php">Sign In Here</a></td>
</tr>
</table>
</form>
</div>
</center>
</body>
</html>


Now, after creating registration page successfully then move ahead to create login page.
i’ve written this login script with little bit security to prevent your website from sql injection.

index.php/login page

this file also contains html form with two input box which will take user email and user password entered by user and then after submitting the form, the php code will match that user email and password combination in database and when it finds both results in table then it will start a session and allow user to access home page else it will show appropriate message.
<?php
session_start();
include_once 'dbconnect.php';

if(isset($_SESSION['user'])!="")
{
 header("Location: home.php");
}
if(isset($_POST['btn-login']))
{
 $email = mysql_real_escape_string($_POST['email']);
 $upass = mysql_real_escape_string($_POST['pass']);
 $res=mysql_query("SELECT * FROM users WHERE email='$email'");
 $row=mysql_fetch_array($res);
 if($row['password']==md5($upass))
 {
  $_SESSION['user'] = $row['user_id'];
  header("Location: home.php");
 }
 else
 {
  ?>
        <script>alert('wrong details');</script>
        <?php
 }
 
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>cleartuts - Login & Registration System</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<center>
<div id="login-form">
<form method="post">
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="email" placeholder="Your Email" required /></td>
</tr>
<tr>
<td><input type="password" name="pass" placeholder="Your Password" required /></td>
</tr>
<tr>
<td><button type="submit" name="btn-login">Sign In</button></td>
</tr>
<tr>
<td><a href="register.php">Sign Up Here</a></td>
</tr>
</table>
</form>
</div>
</center>
</body>
</html>


after registration page and login page we need to create ‘home‘ page which shows users dashboard, which is authentic page and this page cannot access without logging in.

home.php

this page shows welcome message of logged in user with username and a hyper link to logout the user and redirects the ‘logout.php’ page.
<?php
session_start();
include_once 'dbconnect.php';

if(!isset($_SESSION['user']))
{
 header("Location: index.php");
}
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome - <?php echo $userRow['email']; ?></title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
 <div id="left">
    <label>cleartuts</label>
    </div>
    <div id="right">
     <div id="content">
         hi' <?php echo $userRow['username']; ?>&nbsp;<a href="logout.php?logout">Sign Out</a>
        </div>
    </div>
</div>
</body>
</html>


logout.php

this page contains only few lines of php code to unset and destroy the current logged in users session, and after destroying the session the page automatically redirect to the ‘index/login’ page.
<?php
session_start();

if(!isset($_SESSION['user']))
{
 header("Location: index.php");
}
else if(isset($_SESSION['user'])!="")
{
 header("Location: home.php");
}

if(isset($_GET['logout']))
{
 session_destroy();
 unset($_SESSION['user']);
 header("Location: index.php");
}
?>


style.css

style.css file which makes beautify all the pages.
@charset "utf-8";
/* CSS Document */

*
{
 margin:0;
 padding:0;
}
#login-form
{
 margin-top:70px;
}
table
{
 border:solid #dcdcdc 1px;
 padding:25px;
 box-shadow: 0px 0px 1px rgba(0,0,0,0.2);
}
table tr,td
{
 padding:15px;
 //border:solid #e1e1e1 1px;
}
table tr td input
{
 width:97%;
 height:45px;
 border:solid #e1e1e1 1px;
 border-radius:3px;
 padding-left:10px;
 font-family:Verdana, Geneva, sans-serif;
 font-size:16px;
 background:#f9f9f9;
 transition-duration:0.5s;
 box-shadow: inset 0px 0px 1px rgba(0,0,0,0.4);
}

table tr td button
{
 width:100%;
 height:45px;
 border:0px;
 background:rgba(12,45,78,11);
 background:-moz-linear-gradient(top, #595959 , #515151);
 border-radius:3px;
 box-shadow: 1px 1px 1px rgba(1,0,0,0.2);
 color:#f9f9f9;
 font-family:Verdana, Geneva, sans-serif;
 font-size:18px;
 font-weight:bolder;
 text-transform:uppercase;
}
table tr td button:active
{
 position:relative;
 top:1px;
}
table tr td a
{
 text-decoration:none;
 color:#00a2d1;
 font-family:Verdana, Geneva, sans-serif;
 font-size:18px;
}

/* css for home page  */

*
{
 margin:0;
 padding:0;
}
#header
{
 width:100%;
 height:60px;
 background:rgba(00,11,22,33);
 color:#9fa8b0;
 font-family:Verdana, Geneva, sans-serif;
}
#header #left
{
 float:left;
 position:relative;
}
#header #left label
{
 position:relative;
 top:5px;
 left:100px;
 font-size:35px;
}
#header #right
{
 float:right;
 position:relative;
}
#header #right #content
{
 position:relative;
 top:20px;
 right:100px;
 color:#fff;
}
#header #right #content a
{
 color:#00a2d1;
}

/* css for home page */

0 comments:

Post a Comment