PHP Cookie – Simple Example
Constraints
1. Diplay the login form with check box
2. a) If username and password are correct and check box is not selected then display Welcome message
b) When user refresh the page or again type address(url) display the login form
3. a) If username or password are not correct and check box is not selected then display Error message
b) When user refresh the page or again type address(url) display the login form
4. a) If username or password are not correct and check box is selected then display Error message
b) When user refresh the page or again type address(url) display the login form
5. a) If username and password are correct and check box is selected
b) then display Welcome message
c) set the cookie for uname and pwd for specify the expire time
b) When user refresh the page or again type address(url)
Retrive the values from the cookie and then display the welcome message.
<?php
/*
* Author : Antony
* Created on 20-Feb-08
* Program Name : login.php
*/
$uname = $_POST['uname'];
$pwd =$_POST['pwd'];
$flag = $_POST['check'];
if(!isset($_COOKIE['name']) && !isset($_COOKIE['pwd']))
{
if (!isset($uname) && !isset($pwd))
{
loginForm();
}
elseif(check($uname,$pwd) && ($flag == “enabled”))
{
echo “Welcome $uname”;
setcookie(“name”,$uname,time()+120);
setcookie(“pwd”,$pwd,time()+120);
}
else
{
if(check($uname,$pwd))
{
echo “Welcome $uname”;
}
else
{
echo “UnAuthorised”;
}
}
}
else
{
$n = $_COOKIE['name'];
$p = $_COOKIE['pwd'];
if(check($n,$p))
{
echo “Welcome $n”;
}
else
{
echo “UnAuthorised”;
}
}
?>
<?php
function loginForm()
{
?>
<html>
<head>
<title>tLogin Page</title>
</head>
<body bgcolor=”#FFFFFF” text=”#000000″ link=”#FF9966″ vlink=”#FF9966″ alink=”#FFCC99″>
<br/>
<br/>
<br/>
<center>
<form action=”<?php echo $_SERVER['PHP_SELF']; ?>” method=”post” >
User Name <input type=”text” name=”uname” /> <br/><br/>
Password <input type=”password” name=”pwd” /> <br/><br />
<input type=”checkbox” name=”check” value=”enabled”/> Remember Me On This Computer <br /><br>
<input type=”submit” value=”Login”/>
</form>
</center>
</body>
</html>
<?php
}
function check($n,$p)
{
if(($n==”antony”) && ($p == “antony”))
{
return true;
}
else
{
return false;
}
}
?>
