<?php | |
// global variables | |
$pathIndex = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF']; | |
$connection = mysqli_connect('localhost', 'root', '', 'muj_projekt'); | |
mysqli_set_charset($connection, 'utf8'); | |
session_start(); | |
/** | |
* Attemps to log-in the user. | |
* | |
* @param string $username | |
* @param string $password (in plain text) | |
* @return bool TRUE for success, FALSE otherwise | |
*/ | |
function userLogin($username, $password) | |
{ | |
global $connection; | |
$result = mysqli_query($connection, ' | |
SELECT * | |
FROM `users` | |
WHERE `name` = "' . mysqli_real_escape_string($connection, $username) . '"' | |
); | |
$row = mysqli_fetch_assoc($result); | |
if ($row === NULL) { | |
return FALSE; // incorrect username | |
} | |
if (!password_verify($password, $row['password'])) { | |
return FALSE; // incorrect password | |
} | |
session_regenerate_id(TRUE); // prevents session fixation | |
unset($row['password']); | |
$_SESSION['user'] = $row; | |
return TRUE; | |
} | |
/** | |
* Logouts the user. | |
* | |
* @return void | |
*/ | |
function userLogout() | |
{ | |
unset($_SESSION['user']); | |
} | |
/** | |
* Handles log-in request. | |
* | |
* @return void | |
*/ | |
function actionLogin() | |
{ | |
global $pathIndex; | |
$ok = userLogin($_POST['username'], $_POST['password']); | |
$url = $pathIndex . ($ok ? '' : '?incorrect_login=1'); | |
header("Location: $url", TRUE, 303); | |
exit; | |
} | |
/** | |
* Handles log-out request. | |
* | |
* @return void | |
*/ | |
function actionLogout() | |
{ | |
global $pathIndex; | |
userLogout(); | |
header("Location: $pathIndex", TRUE, 303); | |
exit; | |
} | |
if (isset($_POST['username'], $_POST['password'])) { | |
actionLogin($pathIndex); | |
} elseif (isset($_GET['logout'])) { | |
actionLogout($pathIndex); | |
} | |
?> | |
<!doctype html> | |
<meta charset="utf-8"> | |
<?php if (isset($_SESSION['user'])): ?> | |
<p> | |
Přihlášen: <?=htmlspecialchars($_SESSION['user']['name']) ?> (id <?=$_SESSION['user']['id'] ?>) | |
<a href="<?=htmlspecialchars("$pathIndex?logout=1") ?>">odhlásit</a> | |
</p> | |
<?php else: ?> | |
<div> | |
<?php if (isset($_GET['incorrect_login'])): ?> | |
<p style="color: #F00">Zadali jste neplatné uživatelské jméno nebo heslo</p> | |
<?php endif; ?> | |
<form action="index.php" method="post"> | |
Jméno: <input name="username" type="text"><br> | |
Heslo: <input name="password" type="password"><br> | |
<input name="submit" type="submit" value="Přihlásit"> | |
</form> | |
</div> | |
<?php endif; ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment