Here i will show an easy way to authenticate a user.
login.php
session_start();
$errorMessage = '';/*
if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) {
// check if the username and password combination is correct
if ($_POST['txtUserId'] === 'theadmin' && $_POST['txtPassword'] === 'chumbawamba') {
// the username and password match,
// set the session
$_SESSION['basic_is_logged_in'] = true;
// after login we move to the main page
header('Location: main.php');
exit;
} else {
$errorMessage = 'Sorry, wrong username / password';
}
}
But before we start matching the user id and password. We must start the session first. Never forget to start the session before doing anything to the session since it won't work.
You can see above that the hardcoded user id and password are "theadmin" and "chumbawamba". If the submitted user id and password match these two then we set the value of $_SESSION['basic_is_logged_in'] to true. After that we move the application's main page. In this case it's called main.php
If the user id and password don't match we set the error message. This message will be shown on top of the login form.
Note : When starting the session you may stumble upon this kind of error :
Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at C:\Webroot\examples\user-authentication\basic\login.php:1) in C:\Webroot\examples\user-authentication\basic\login.php on line 3
PHP will spit this error message if the script that call session_start() already send something ( a blank space, newline, etc ). The error above happen when i add a single space on the first line right before the php opening tag (
*/
?>
if ($errorMessage != '') {
?>
echo $errorMessage; ?>
}
?>
main.php
// like i said, we must never forget to start the session
session_start();
// is the one accessing this page logged in or not?
if (!isset($_SESSION['basic_is_logged_in'])
|| $_SESSION['basic_is_logged_in'] !== true) {
// not logged in, move to login page
header('Location: login.php');
exit;
}
?>
/// Your conte here
logout.php
// i will keep yelling this
// DON'T FORGET TO START THE SESSION !!!
session_start();
// if the user is logged in, unset the session
if (isset($_SESSION['basic_is_logged_in'])) {
unset($_SESSION['basic_is_logged_in']);
}
// now that the user is logged out,
// go to login page
header('Location: login.php');
?>
Hope you have understood the basic of php authentication now on my next tutorial i will show you how to authenticate using MYSQL and Session which is the best way .
No comments:
Post a Comment