index.php
<?php
include('./classes/DB.php');
function isLoggedIn() {
if(isset($_COOKIE['SNID'])) {
if(DB::query('SELECT
user_id FROM login_tokens WHERE token=:token',
array(':token'=>sha1($_COOKIE['SNID'])))) {
$userid =
DB::query('SELECT user_id FROM login_tokens WHERE token=:token',
array(':token'=>sha1($_COOKIE['SNID'])))[0]['user_id'];
return $userid;
}
}
return false;
}
if(isLoggedIn()) {
echo 'Logged in';
echo isLoggedIn();
} else {
echo 'Not logged in';
}
?>
Зададим вторые
куки на 3 дня в фале login.php
<?php
ob_start(); // от ошибки
include('classes/DB.php');
if(isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (DB::query('SELECT username FROM users WHERE username=:username',
array(':username'=>$username))) {
if (password_verify($password, DB::query('SELECT password
FROM users WHERE username=:username',
array(':username'=>$username))[0]['password'])) {
echo 'Logged in!';
// при входе на сайт мы генерируем
токен
$cstrong = true;
$token = bin2hex(openssl_random_pseudo_bytes(64,
$cstrong)); // мы генерируем 64 байта, вторым
параметром передается только переменая
// echo $token; //
3df3d89336887cd8701b391ab5a8cd1b81205dcd1b9f51ed4d15815690cda971b19685bea37632c17d895bef95d2076c1d463697757a301828791ce1061ef43b
$user_id = DB::query('SELECT id
FROM users WHERE username=:username',
array(':username'=>$username))[0]['id'];
DB::query('INSERT INTO login_tokens VALUE (:id,
:token, :user_id)', array(':id'=>null, ':token'=>sha1($token),
':user_id'=>$user_id));
setcookie("SNID", $token, time() + 60 *
60 * 24 * 7, '/', NULL, NULL, TRUE);
setcookie("SNID_",
'1', time() + 60 * 60 * 24 * 3, '/', NULL, NULL, TRUE);
} else {
echo 'Incorrect Password!';
}
} else {
echo 'User not registered!';
}
}
?>
<h1>Login
to your account</h1>
<form
action="login.php" method="post">
<input type="text" name="username"
placeholder="Username..."/> </p>
<input type="password" name="password"
placeholder="Password..."/> </p>
<input type="submit" name="login"
value="Login"/>
</form>
index.php
<?php
include('./classes/DB.php');
function isLoggedIn()
{
if(isset($_COOKIE['SNID'])) {
if(DB::query('SELECT user_id FROM login_tokens WHERE token=:token',
array(':token'=>sha1($_COOKIE['SNID'])))) {
$userid =
DB::query('SELECT user_id FROM login_tokens WHERE token=:token',
array(':token'=>sha1($_COOKIE['SNID'])))[0]['user_id'];
if(isset($_COOKIE['SNID_'])) {
return
$userid;
} else {
//
если прошло 3 дня и куки истекли, мы
генерируем токен
$cstrong = true;
$token
= bin2hex(openssl_random_pseudo_bytes(64, $cstrong)); // мы
генерируем 64 байта, вторым параметром
передается только переменая
DB::query('INSERT INTO login_tokens VALUE (:id, :token, :user_id)',
array(':id'=>null, ':token'=>sha1($token),
':user_id'=>$userid));
DB::query('DELETE FROM login_tokens WHERE token=:token',
array(':token'=>sha1($_COOKIE['SNID'])));
setcookie("SNID", $token, time() + 60 * 60 * 24 * 7, '/',
NULL, NULL, TRUE);
setcookie("SNID_", '1', time() + 60 * 60 * 24 * 3, '/',
NULL, NULL, TRUE);
return
$userid;
}
}
}
return false;
}
if(isLoggedIn()) {
echo 'Logged in';
echo isLoggedIn();
} else {
echo 'Not logged
in';
}
?>
Исправим
регистрацию create-account.php
Исключим
повторяемость имейлов.
<?php
include('classes/DB.php');
if(isset($_POST['createaccount']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if(!DB::query('SELECT username FROM users WHERE username=:username',
array(':username'=>$username))) {
if(strlen($username) >= 3 && strlen($username) <= 32)
{
if(preg_match('/[a-zA-Z0-9_]+/', $username)) {
if(strlen($password) >= 6 && strlen($password)
<= 60) {
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
if(!DB::query('SELECT email FROM users WHERE
email=:email', array(':email'=>$email))) {
DB::query('INSERT INTO users VALUES (:id, :username, :password,
:email)', array(':id'=>null, ':username'=>$username,
':password'=>password_hash($password, PASSWORD_BCRYPT),
':email'=>$email));
echo "Success!";
}
else {
echo 'Email in use!';
}
} else {
echo 'Invalid email!';
}
} else {
echo 'Invalid password!';
}
} else {
echo 'Invalid username!';
}
} else {
echo 'Invalid username!';
}
}
else {
echo 'User already exists!';
}
}
?>
<h1>Register</h1>
<form
action="create-account.php" method="post">
<p><input type="text" name="username"
placeholder="Username"/></p>
<p><input type="password" name="password"
placeholder="Password"/></p>
<p><input type="email" name="email"
placeholder="someone@somesite.com"/></p>
<input type="submit" name="createaccount"
value="Create Account"/>
</form>
Комментариев нет:
Отправить комментарий