10 Oct, 2018
Categories: PHP
Login Form Page
Create new PHP file use for processing login with cookies as below:
<?php
session_start();
if(isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
if($_COOKIE['username']=='abc' && $_COOKIE['password']=='123') {
$_SESSION['username'] = $_COOKIE['username'];
header('location:welcome.php');
}
else
$error = "Account's Invalid";
}
if(isset($_POST['login'])){
if($_POST['username']=='abc' && $_POST['password']=='123'){
$_SESSION['username'] = $_POST['username'];
if($_POST['remember'] != NULL) {
setcookie('username', $_POST['username'], time() + (86400 * 30), "/");
setcookie('password', $_POST['password'], time() + (86400 * 30), "/");
}
header('location:welcome.php');
}
else {
$error = "Account's Invalid";
}
}
?>
<form method="post">
<fieldset>
<legend>Login</legend>
<?php echo isset($error) ? $error : ''; ?>
<table cellpadding="2" cellspacing="2">
<tr>
<td>Username</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td>Remember Me</td>
<td><input type="checkbox" name="remember"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="login" value="Login"></td>
</tr>
</table>
</fieldset>
</form>
Welcome Page
Create PHP file named welcome.php. This file display value from Session as below:
<?php
session_start();
if(isset($_GET['action']) && $_GET['action']=='logout'){
// Remoce session
unset($_SESSION['username']);
// Remoce cookie
setcookie('username', '', 0, "/");
setcookie('password', '', 0, "/");
header('location:index.php');
}
echo 'Welcome '.$_SESSION['username'];
?>
<br>
<a href="welcome.php?action=logout">Logout</a>
Demo
Login Page
Welcome Page
References
I recommend you refer to the books below to learn more about the knowledge in this article:
- Murach’s PHP and MySQL (3rd Edition)
- Learning PHP, MySQL & JavaScript: With jQuery, CSS & HTML5 (Learning Php, Mysql, Javascript, Css & Html5)
- PHP and MySQL Web Development (5th Edition) (Developer’s Library)
- Murach’s MySQL, 2nd Edition
- MySQL (5th Edition) (Developer’s Library)
- PHP Ajax Cookbook