Tuesday, December 18, 2012

A simple PHP login system

To build a simple PHP login system. Here we used PHP session to login and logout, and a form and MySQl database to manage user login.
First we need to create a user table and create two entries
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(20) NOT NULL,
  `pwd` varchar(64) NOT NULL,
  `email` varchar(50) NOT NULL,
  `lasttime` datetime NOT NULL,
  `regtime` date NOT NULL,
  PRIMARY KEY  (`id`)

INSERT INTO `user` VALUES (1, 'admin', '123456', 'admin@example.com',
'0000-00-00 00:00:00', '0000-00-00');
INSERT INTO `user` VALUES (2, 'jiansen', '123456', 'jiansen@example.com',
 '0000-00-00 00:00:00', '0000-00-00');

config.inc.php to connect to database
 //Example of using MySQL in PHP 
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "test";
{echo "connect to MySQL server ".$db_host."<br />";}
else die ("could not connect to mysql");
{echo "connect to dtabase ".$db_name."<br />";}
else die("no database");            

login.html to post a from using  login.php
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>User Login</title>
<form name="Login" method="post" action="login.php">
<table border="0" cellpadding="8" width="350" align="center">
        <td colspan="2" align="center" class="alert">User Login Interface</td>
   <td><input name="username" type="text" id="username" class="textinput" /></td>
    <td><input name="pwd" type="password" id="pwd" class="textinput" /></td></tr>
    <tr><td colspan="2" align="center">
    <input type="submit" class="btn" value="login">&nbsp;&nbsp;
    <input type="reset" class="btn" value="reset">

//remove white space and prevent MySQL injection
$username = addslashes(trim($_POST['username']));
$password = addslashes(trim($_POST['pwd']));
 if (empty($username)||empty($password)){
 echo "User name or password is empty";
       $sql = "SELECT * FROM user WHERE username='$username' AND pwd='$password'";
            $result = mysql_query($sql);
           if ($result && mysql_num_rows($result)==1) {             
                $_SESSION['login'] = 'true';
                echo "User ".$username." log in";
                 echo "User ".$username." not matched";

is_login.php to test if user already login
if (empty($_SESSION['login'])) {
    echo "You are not login";
    echo "You are  login";

 unset( $_SESSION['login']);
 echo "You are log out";

Vedio for this demo: 

No comments:

Post a Comment