In this tutorial I will explain you, how to write a simple php script, for what registered users can login into website and also can logout.
Php
Basic
This tutorial is basically for beginners, those who searching for php login script. So, in this tutorial I will explain you, how to write a simple php script, for what registered users can login into website and also can logout. Here, also you can learn about php $_SESSION[] variable, by which you can store user data into $_SESSION variable and can access any where from your website.
Let’s check the code —db.php
<?php
define('HOSTNAME','localhost');
define('DB_USERNAME','root');
define('DB_PASSWORD',password');
define('DATABASE','databasename');
$link = mysql_connect(constant('HOSTNAME'), constant('DB_USERNAME'), constant('DB_PASSWORD')) or die("Database connection error, please check!");
mysql_select_db(constant('DATABASE'), $link) or die("Connection to the defined database not possible, please check!");
?>
Change your database username, password and database name as you specified.
<div id="hints">Try USERNAME : <strong>username</strong> & PASSWORD : <strong>password</strong></div>
<div class="loginDiv">
<div id="title"> Login Form</div>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<table width="299" border="0">
<td width="108">Username :</td>
<td width="181"><input type="text" name="username" value="" size="30" /></td>
</tr>
<tr>
<td>Password :</td>
<td><input type="password" name="password" value="" size="30" /></td>
</tr>
<tr>
<td> </td>
<td align="right"><input type="submit" value="Login" /></td>
</tr>
<tr>
<td colspan="2"><span><?php echo $msg;?></span></td>
</tr>
</table>
</form>
</div>
Above code is for login form, where user can give input their username and password. If you want to redirect to the same page, you can use $_SERVER['PHP_SELF'].
<?php
$msg = "";
if(isset($_GET['msg']) && $_GET['msg'] != "") $msg = $_GET['msg'];
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$username = $_POST['username'];
$password = $_POST['password'];
$query = "select * from `users` where `username` = '".$username."' and `password` = '".$password."' ";
$res = mysql_query($query);
if(mysql_num_rows($res) > 0)
{
$row = mysql_fetch_array($res);
//Here we can assign more or less $_SESSION variable as per our need
$_SESSION['uid'] = $row['uid'];
$_SESSION['uname'] = $row['username'];
$_SESSION['fname'] = $row['f_name'];
$_SESSION['lname'] = $row['l_name'];
//After session created you can redirect to any other page instead index.php,
//then last if else part is not required
}
else
{
//Display, if username and/or password is wrong.
$msg = "<span>Invalid username or password! Please try again.</span>";
}
}
?>
At the above code snippet I have just received the username and password from login form which were just entered by user. And then process a query to check whether any user with these username and password is exists or not. If exists, then user data are stored in different $_SESSION[] variables, such as, uid of the user is stored in $_SESSION['uid'] variable. You can assign anything instead “uid” within the $_SESSION[] variable, just remember, when you try to retrieve the uid of the user through session variable, you have to specify the variable name you assigned within the $_SESSION['']. And one more thing, when ever you worked with session variables, you have to write session_start() function at the top.
//Display "Welcome Bhagat Singh!" and a Logout option after successful login.
echo "<span id='welc'>Welcome ".$_SESSION['fname']." ".$_SESSION['lname']."!</span>";
echo "<a href='logout.php'>Logout</a>";
After successful login, a message will display to the user with his name, and a Logout option.
So, combined all the above codes we get,index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Php login script tutorial</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<?php
include('db.php');
//Whenever we deal with session, we have to define the follwing function
session_start();
?>
<?php
$msg = "";
if(isset($_GET['msg']) && $_GET['msg'] != "") $msg = $_GET['msg'];
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$username = $_POST['username'];
$password = $_POST['password'];
$query = "select * from `users` where `username` = '".$username."' and `password` = '".$password."' ";
$res = mysql_query($query);
if(mysql_num_rows($res) > 0)
{
$row = mysql_fetch_array($res);
//Here we can assign more or less $_SESSION variable as per our need
$_SESSION['uid'] = $row['uid'];
$_SESSION['uname'] = $row['username'];
$_SESSION['fname'] = $row['f_name'];
$_SESSION['lname'] = $row['l_name'];
//After session created you can redirect to any other page instead index.php,
//then last if else part is not required
}
else
{
//Display, if username and/or password is wrong.
$msg = "<span>Invalid username or password! Please try again.</span>";
}
}
?>
<?php
//Check whether session is set or not, if not the login form will display, otherwise else part
if(!$_SESSION)
{
?>
<div id="tuto_link">Tutorial link: <a href="http://www.invlessons.com/php-login-script-tutorial/">PHP login script tutorial</a></div>
<div id="hints">Try USERNAME : <strong>username</strong> & PASSWORD : <strong>password</strong></div>
<div class="loginDiv">
<div id="title"> Login Form</div>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<table width="299" border="0">
<td width="108">Username :</td>
<td width="181"><input type="text" name="username" value="" size="30" /></td>
</tr>
<tr>
<td>Password :</td>
<td><input type="password" name="password" value="" size="30" /></td>
</tr>
<tr>
<td> </td>
<td align="right"><input type="submit" value="Login" /></td>
</tr>
<tr>
<td colspan="2"><span><?php echo $msg;?></span></td>
</tr>
</table>
</form>
</div>
<?php
}
else
{
//Display "Welcome Bhagat Singh!" and a Logout option after successful login.
echo "<span id='welc'>Welcome ".$_SESSION['fname']." ".$_SESSION['lname']."!</span>";
echo "<a href='logout.php'>Logout</a>";
}
?>
</body>
</html>
logout.php
<?php
session_start();
//By three way we can destroy session
//1
/*unset($_SESSION['uid']);
unset($_SESSION['uname']);
unset($_SESSION['fname']);
unset($_SESSION['lname']);*/
//2
/*$_SESSION['uid'] = "";
$_SESSION['uname'] = "";
$_SESSION['fname'] = "";
$_SESSION['lname'] = "";*/
//3
//Through this function we can destroy all session variables at a time.
session_destroy();
header('location: index.php?msg=Thank you, visit again.');
?>
During logout we can destroy user’s data from session variables by three way as described in the code snippet. Such as unset and session_destroy().