Skip to content

Instantly share code, notes, and snippets.

@JanTvrdik
Last active December 9, 2019 11:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JanTvrdik/8d813cfc7a4a8e0db2c7 to your computer and use it in GitHub Desktop.
Save JanTvrdik/8d813cfc7a4a8e0db2c7 to your computer and use it in GitHub Desktop.
<?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