Showing posts with label PHP Login page. Show all posts
Showing posts with label PHP Login page. Show all posts

Monday, 20 July 2015

PHP: Ajax PHP Login Page with bootstrap design

Database
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(100) NOT NULL,
  `password` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
)

Bootstrap code
Add below code in index file <head></head> tag
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>

Html
Bootstrap form i have take sample bootstrap form in bootstrap website.
<body>
  <div class="modal-dialog">
    <div class="modal-content col-md-8">
      <div class="modal-header">
        <h4 class="modal-title"><i class="icon-paragraph-justify2"></i> User Login</h4>
      </div>
      <form method="post" id="login_form">
        <div class="modal-body with-padding">
          <div class="form-group">
            <div class="row">
              <div class="col-sm-10">
                <label>Username *</label>
                <input type="text" id="username" name="username" class="form-control required">
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="row">
              <div class="col-sm-10">
                <label>Password *</label>
                <input type="password" id="password" name="password" class="form-control required" value="">
              </div>
            </div>
          </div>
        </div>
        <div class="error" id="logerror"></div>
        <!-- end Add popup  --> 
        <div class="modal-footer">
          <input type="hidden" name="id" value="" id="id">
          <button type="submit" id="btn-login" class="btn btn-primary">Submit</button>             
        </div>
      </form>
    </div>
  </div>
</body>

Html & ajax code
Above form we seialize() data to pass ajax.php file. if post data (username,password) available page redirect to profile php. Add below code under the above form.
$('#login_form').validate(); - Validate to login form.
<script> 
$(document).ready(function(){
  $('#login_form').validate();  
  $(document).on('click','#btn-login',function(){
    var url = "login.php";      
    if($('#login_form').valid()){
      $('#logerror').html('<img src="ajax.gif" align="absmiddle"> Please wait...'); 
      $.ajax({
      type: "POST",
      url: url,
      data: $("#login_form").serialize(), // serializes the form's elements.
      success: function(data)
      {
        if(data==1) {              
              window.location.href = "profile.php";
        }
        else {  $('#logerror').html('The email or password you entered is incorrect.');
              $('#logerror').addClass("error"); }
        }
        });
    }
    return false;
  });
});
</script>

login.php
extract($_POST); it will convert serialize data to array data.
mysqli_real_escape() string -  check post data special characters.
$db - Database config
<?php
$db = new mysqli('localhost', 'root', '', 'mostlikers');
session_start();
    if($_POST['username']!="" && $_POST['password']!=""):
        extract($_POST);
        $username=mysqli_real_escape_string($db,$_POST['username']);
        $pass_encrypt=md5(mysqli_real_escape_string($db,$_POST['password']));
        $fetch=$db->query("SELECT * FROM `users` WHERE username='$username' AND `password` = '$pass_encrypt'");
        $count=mysqli_num_rows($fetch);
        if($count=="1") :
           $row=mysqli_fetch_array($fetch);
           $_SESSION['login_username']=$row['username'];   
           echo 1; 
        else :
          echo 0;
        endif;
    else :
        header("Location:index.php");
    endif;
?>


profile.php
If user session value is empty, this will redirect to index page.
<?php
session_start();
$check=$_SESSION['login_username'];
if(!isset($check))
{
    header("Location:index.php");
}
?>
<h3 align="center"> Hellow <?php echo $_SESSION['login_username']; ?></h3>
<h2 align="center" >Welcome to mostlikers</h2>
<h4 align="center">  click here to <a href="logout.php">LogOut</a>
</h4>

logout.php
It clear all session data after data clean redirect to login page.
<?php
session_start();
if(session_destroy())
{
header("Location: index.php");
}
?>

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 */

Thursday, 4 June 2015

PHP: Complete, simple, working example of a login screen system using php functions, cookies, and a mysql database for begginers.

<?php
// This first if statement checks to see if we have a username/pass submited by the form, if it does then it attempts to validate it.
if($username && $password) {
  mysql_connect() or die ("Whoops");    // Connect to the database, or if connection fails print error message.
  $password = md5($password);          // encode submited password with MD5 encryption and store it back in the same variable. If not on a windows box, I
suggest you use crypt()
  $sql = "select * from login where username='$username'";   // query statment that gets the username/password from 'login' where the username is the same as
the one you
submited
  $r = mysql_db_query("register",$sql);  // Execute Query

  // if no rows for that database come up, redirect.
  if(!mysql_num_rows($r))
    header("Location: $SCRIPT_NAME");  // This is the redirection, notice it uses $SCRIPT_NAME which is a predefined variable with the name of the script in it.

  $user = mysql_fetch_array($r);  // if we got passed the last if statment means we have a registered username, get the rest of the info and put it in an array
named $user
  if($user["password"] == $password) {   // If the password stored in the database is the same as the password the user entered (which is now encryped with MD5)
    $password = serialize($password);  // if we get this far we know we have a registered username, and the password matches.
                                                      // serialize() the already incrypted password just for fun and mabey some extra security for when we
store it in a cookie
    setcookie("candle_login","$username $password");  // Set the cookie named 'candle_login' with the value of the username (in plain text) and the password
(which has been
encrypted and serialized.)

// set variable $msg with an HTML statement that basically says redirect to the next page. The reason we didn't use header() is that using setcookie() and
header() at the same
time isn't 100% compatible with all browsers, this is more compatible.

    $msg = "<meta http-equiv=\"Refresh\" content=\"0;url=./nextpage.php\">";
  }else{
     header("Location: $SCRIPT_NAME");  //If the password didn't match, redirect to this page in which $username and $password are reset therefore the first if
() never gets executed
  }
}
if($msg) echo $msg;  //if $msg is set echo it, resulting in a redirect to the next page.
?>

// This is the login screen
<html>
<title>Login</title>
<body bgcolor="yellow" text="black">
<form method="post" action="<?echo $SCRIPT_NAME;?>"> // submit form data to this page

<center><font size=+5><b>Welcome!</b></font></center>
<br>
<br>
<br>
<table cellspacing=0 cellpadding=0 width=320 align="center">
<tr><td>
Username:
</td><td>
<input name="username" type="text" width=10>
</td></tr>
<tr><td>
Password:
</td><td>
<input name="password" type="password" width=10>
</td></tr>
<tr><td colspan=2 align="center">
<input name="login" type="submit">
</td></tr>
</table>
</form>
</html>


/* That was the login page
    Next is some code you can put into a different file (named 'login_check.inc' or something)
    that you include() on each page you want protected on your site.
    It uses the cookie from the first script to verify user has already been there.
*/

<?php
// if the cookie doesn't exsist means the user hasn't been verified by the login page so send them back to the login page.
if(!$candle_login)
  header("Location: ./login.php");

if($phpcoders) {     // if the cookie does exsist
  mysql_connect() or die ("Whoops");  //connect to db
  $user = explode(" ","$phpcoders");   //explode cookie value (which is the '$username $password (note seperated by space)) and store values in $user. Check
manual for more info
on explode()

  $sql = "select * from login where username='$user[0]'";  //sql statment that uses the username from the cookie.
  $r = mysql_db_query("register",$sql);  //execute sql

  if(!mysql_num_rows($r)) {    // if there are no rows, means no matches for that username
    header("Location: ./login.php");   // so go back to the login page
  }

  $chkusr = mysql_fetch_array($r); //if we got passed the last part, then get the username/password set that match that username
  if(unserialize($user[1]) != $chkusr[1]) //if the password from cookie (notice we have to unserialize it) doesn't match the one from the database
    header("Location: ./login.php");       // go back to the login page
}                                                     // if it did match then continue on to page and this ends up doing nothing :)
?>

PHP: Complete, simple working example of login screen and check on a unique page using php functions, cookies and mysql database.

Complete, simple working example of login screen and check on a unique
page using php functions, cookies and mysql database.

<?php

if (!$mysql_login)   {
        // check if $username and $password are passed through as query string
    if($username && $password) {
        include("./dbConn.php3");  
            // If you want to have the passwords in the databases crypted.
        $password = md5($password);  

        $loc="Location: http://$SERVER_NAME$SCRIPT_NAME";.
        $sql = "select Password from users_t where Username='$username'";
        $r = mysql_db_query($db,$sql);

            //check if the result of the query has at least one row.Or it will redirect the page.
        if(!mysql_num_rows($r)) header($loc);  

        $user = mysql_fetch_array($r);
        if($user["Password"] == $password) {
                //note the space between the username and the passoword. It will be
                //used below to slice the cookie.
            setcookie("mysql_login","$username $password");  
        $msg = "<meta http-equiv=\"Refresh\" content=\"0;url=$SCRIPT_NAME\">";
        //The use of the http header is inconsistent with many browser if you have
                //already setted a cookie. So, after the setcookie command the script uses
                //the meta tag to obtain the same result.
        }else{
        header($loc);
        }
    }else{
?>

        <html>
        <title>Login to PHP Coders DB</title>
        <body bgcolor="yellow" text="black">
        <form method="post" action="<?php echo($SCRIPT_NAME)?>">
        <center><font size=+5><b>Welcome!</b></font></center>
        <br><br><br>
        <table cellspacing=0 cellpadding=0 width=320 align="center">
        <tr><td>Username:</td><td>
        <tr><td><input name="username" type="text" width=10></td></tr>
        <tr><td>Password: </td><td>
        <tr><td><input name="password" type="password" width=10></td></tr>
        <tr><td colspan=2 align="center"><input name="login" type="submit"></td></tr>
                </form>        
                </table>
        <body>
        </html>

        <?php
        die(); //This will prevent PHP from showing actual page. See above.
    }
}else{
    //include("./dbConn.php3");  
    $chk=0;
        // Set an array called $user with the contents of the cookie
        //sliced at the space between username and password, see above.
    $user = explode(" ","$mysql_login");  
    $sql = "select Password from users_t where username='$user[0]'";  
    $r = mysql_db_query($db,$sql);

        //check if the result of the query has at least one row.Or it set the $chk variable.
    if(!mysql_num_rows($r)) $chk=1;  
    $chkusr = mysql_fetch_array($r);
    if ($user[1]!=$chkusr["Password"]) $chk=1;
    if ($chk) {
            // To reset the cookie, the setcookie function is used here without argoument.  
        setcookie("mysql_login");
            // see above.
        echo("<meta http-equiv=\"Refresh\" content=\"0;url=$SCRIPT_NAME\">");
    }

}

//After here the actual page starts and only registered user can see it.
?>