logo

  • Hỏi Đáp
  • Kiến Thức
  • Sức Khỏe
  • Tử Vi
  • Công Nghệ
No Result
View All Result
logo
No Result
View All Result
Trang chủ php simple login & remember me script using cookies

PHP SIMPLE LOGIN & REMEMBER ME SCRIPT USING COOKIES

by Admin _ June 11, 2022

Login Script with ‘Remember Me’ feature will allow the user lớn preserve their logged in status. When the user checks the Remember Me option, then the logged in status is serialized in the PHP session or cookies lượt thích storages.

Bạn đang xem: Php simple login & remember me script using cookies

While writing user login data in the session or cookie we need to lớn be aware of the security breaches which might compromise the application’s authentication system. Plain passwords should not be stored in the user’s cookie, this will allow hacking the application.

This example will help you lớn build a persistent authentication system for your PHP website application. When the user attempts to lớn log in with the application, the entered login credentials are verified with the database.

If a match is found, the PHP session and the cookies are used lớn preserve user logged-in state before redirecting the user to the dashboard. On successful login, the unique member id from the thành viên database is stored in a session.

Then, the cookies are set to lớn keep the login name & the password for a specified expiration period. Instead of storing the users’ plain password, random password và token are generated & stored in the cookie to avoid hacking.

When the user accessing the application pages, the existing logged in session is checked to redirect the user to lớn access the requested page. If the session is empty, then the code will kiểm tra the logged-in with the cookies. If both the session and the cookies are not having any data about the remembered login, then the user will be redirected back to the login page.

This screenshot shows the UI for the secured Remember Me with a login form.

*

The authentication cookies are set with the expiration time of 1 month. The random password và tokens will be stored in the database with the expiration date & time. The cookie-based logged in state validation is done by testing cookie availability and expiration stored in the database.

Create Cookies khổng lồ Preserve the Logged-In State

I have created a login size to get the username và password. This form contains a checkbox captioned as ‘Remember Me’ to lớn allow the user to preserve his logged in status. When the user submits the login data, the posted details are received in PHP và validated with the thành viên database.

On successful login, if the user selected ‘Remember Me’ then the logged-in status is stored in PHP session & cookies.

Xem thêm: Cung Hoàng Đạo Lanh Lung Nhat, Cung Hoàng Đạo Nữ Nào Lạnh Lùng Nhất

As it is a security loophole to lớn store the plain password in the cookie, the random numbers are generated as the authentication keys. These keys are hashed and stored in the database with an expiration period of 1 month. Once the time expires, then the expiration flag will be set lớn 0 và the keys will be deactivated.

redirect("dashboard.php");}if (! empty($_POST<"login">)) $isAuthenticated = false; $username = $_POST<"member_name">; $password = $_POST<"member_password">; $user = $auth->getMemberByUsername($username); if (password_verify($password, $user<0><"member_password">)) $isAuthenticated = true; if ($isAuthenticated) $_SESSION<"member_id"> = $user<0><"member_id">; // mix Auth Cookies if "Remember Me" checked if (! empty($_POST<"remember">)) setcookie("member_login", $username, $cookie_expiration_time); $random_password = $util->getToken(16); setcookie("random_password", $random_password, $cookie_expiration_time); $random_selector = $util->getToken(32); setcookie("random_selector", $random_selector, $cookie_expiration_time); $random_password_hash = password_hash($random_password, PASSWORD_DEFAULT); $random_selector_hash = password_hash($random_selector, PASSWORD_DEFAULT); $expiry_date = date("Y-m-d H:i:s", $cookie_expiration_time); // mark existing token as expired $userToken = $auth->getTokenByUsername($username, 0); if (! empty($userToken<0><"id">)) $auth->markAsExpired($userToken<0><"id">); // Insert new token $auth->insertToken($username, $random_password_hash, $random_selector_hash, $expiry_date); else $util->clearAuthCookie(); $util->redirect("dashboard.php"); else $message = "Invalid Login"; ?>This the HTML code to display the login form with ‘Remember Me’ option.


Validate Remembered Login with PHP Session and Cookies

A PHP page authCookieSessionValidate.php contains the session & cookie-based logged-in state validation code. It is included at the beginning of the application pages for which the user needs to be authenticated.

If the logged-in state exists with the session or cookie array, then this code will phối $loggedIn flag khổng lồ true. Based on this boolean value, the user will be allowed lớn proceed with the application or redirected back to the login page.

First, the remembered login is checked with the PHP session. If it returns false, then the code will tìm kiếm for the authentication keys stored in the cookies. If the keys are not empty then they will be hashed compared with the database.

Once the match found then the expiration date is validated with the current date và time. Once the code passes through with all the validation, the user will be redirected to lớn the dashboard.

getTokenByUsername($_COOKIE<"member_login">,0); // Validate random password cookie with database if (password_verify($_COOKIE<"random_password">, $userToken<0><"password_hash">)) $isPasswordVerified = true; // Validate random selector cookie with database if (password_verify($_COOKIE<"random_selector">, $userToken<0><"selector_hash">)) $isSelectorVerified = true; // check cookie expiration by date if($userToken<0><"expiry_date"> >= $current_date) $isExpiryDateVerified = true; // Redirect if all cookie based validation retuens true // Else, mark the token as expired & clear cookies if (!empty($userToken<0><"id">) && $isPasswordVerified && $isSelectorVerified && $isExpiryDateVerified) $isLoggedIn = true; else if(!empty($userToken<0><"id">)) $auth->markAsExpired($userToken<0><"id">); // clear cookies $util->clearAuthCookie(); }?>

Clear Remembered Login with Session và Cookies on Logout

In the dashboard screen, it contains the welcome text with the logout link. On clicking the logout link, the remembered login state will be unset from the PHP session và cookies.

clearAuthCookie();header("Location: ./");?>

Database Script

Import this SQL script to chạy thử this example in your local environment. After mix up, try login with admin/admin as the username & the password.

---- Database: `db_auth`---- ------------------------------------------------------------ Table structure for table `members`--CREATE TABLE `members` ( `member_id` int(8) NOT NULL, `member_name` varchar(255) CHARACTER phối utf8 NOT NULL, `member_password` varchar(64) NOT NULL, `member_email` varchar(255) CHARACTER phối utf8 NOT NULL) ENGINE=InnoDB default CHARSET=latin1;---- Dumping data for table `members`--INSERT INTO `members` (`member_id`, `member_name`, `member_password`, `member_email`) VALUES(1, "admin", "$2a$10$0FHEQ5/cplO3eEKillHvh.y009Wsf4WCKvQHsZntLamTUToIBe.fG", "user
gmail.com");-- ------------------------------------------------------------ Table structure for table `tbl_token_auth`--CREATE TABLE `tbl_token_auth` ( `id` int(11) NOT NULL, `username` varchar(255) NOT NULL, `password_hash` varchar(255) NOT NULL, `selector_hash` varchar(255) NOT NULL, `is_expired` int(11) NOT NULL default "0", `expiry_date` timestamp NOT NULL default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP) ENGINE=InnoDB mặc định CHARSET=latin1;---- Indexes for dumped tables------ Indexes for table `members`--ALTER TABLE `members` địa chỉ PRIMARY KEY (`member_id`);---- Indexes for table `tbl_token_auth`--ALTER TABLE `tbl_token_auth` địa chỉ cửa hàng PRIMARY KEY (`id`);---- AUTO_INCREMENT for dumped tables------ AUTO_INCREMENT for table `members`--ALTER TABLE `members` MODIFY `member_id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;---- AUTO_INCREMENT for table `tbl_token_auth`--ALTER TABLE `tbl_token_auth` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17;COMMIT;

Auth và DBController Classes

These are the classes used lớn trigger and handle database operations. The database querying is performed efficiently with the MySQLi prepared statement.

Auth.php

runQuery($query, "s", array($username)); return $result; } function getTokenByUsername($username,$expired) $db_handle = new DBController(); $query = "Select * from tbl_token_auth where username = ? và is_expired = ?"; $result = $db_handle->runQuery($query, "si", array($username, $expired)); return $result; function markAsExpired($tokenId) $db_handle = new DBController(); $query = "UPDATE tbl_token_auth mix is_expired = ? WHERE id = ?"; $expired = 1; $result = $db_handle->update($query, "ii", array($expired, $tokenId)); return $result; function insertToken($username, $random_password_hash, $random_selector_hash, $expiry_date) $db_handle = new DBController(); $query = "INSERT INTO tbl_token_auth (username, password_hash, selector_hash, expiry_date) values (?, ?, ?,?)"; $result = $db_handle->insert($query, "ssss", array($username, $random_password_hash, $random_selector_hash, $expiry_date)); return $result; function update($query) mysqli_query($this->conn,$query); }?>DBController.php

conn = $this->connectDB();}function connectDB() $conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);return $conn; function runBaseQuery($query) $result = mysqli_query($this->conn,$query); while($row=mysqli_fetch_assoc($result)) $resultset<> = $row; if(!empty($resultset)) return $resultset; function runQuery($query, $param_type, $param_value_array) $sql = $this->conn->prepare($query); $this->bindQueryParams($sql, $param_type, $param_value_array); $sql->execute(); $result = $sql->get_result(); if ($result->num_rows > 0) while($row = $result->fetch_assoc()) $resultset<> = $row; if(!empty($resultset)) return $resultset; function bindQueryParams($sql, $param_type, $param_value_array) $param_value_reference<> = & $param_type; for($i=0; $iconn->prepare($query); $this->bindQueryParams($sql, $param_type, $param_value_array); $sql->execute(); function update($query, $param_type, $param_value_array) $sql = $this->conn->prepare($query); $this->bindQueryParams($sql, $param_type, $param_value_array); $sql->execute(); }?>Download

Share Tweet Linkedin Pinterest
Previous Post

Install apache, mysql 8 or mariadb 10 and php 7 on centos 7

Next Post

Select data then add to database

CÙNG CHUYÊN MỤC

form register php

Form register php

09/04/2021
fantastic blog (cms) in php with source code

Fantastic blog (cms) in php with source code

28/04/2021
validate form php javascript

Validate form php javascript

28/04/2021
http diendanlequydon com viewtopic php style 6

Http diendanlequydon com viewtopic php style 6

28/04/2021
phần mềm lập trình php tốt nhất

Phần mềm lập trình php tốt nhất

01/07/2022
ghi file trong php

Ghi file trong php

30/06/2022
thực tập part time php hà nội

Thực tập part time php hà nội

30/06/2022
test preg_match online

Test preg_match online

30/06/2022

Newsletter

The most important automotive news and events of the day

We won't spam you. Pinky swear.

Chuyên Mục

  • Hỏi Đáp
  • Kiến Thức
  • Sức Khỏe
  • Tử Vi
  • Công Nghệ

News Post

  • Cách cắm hoa hong đẹp và đơn giản

About

Chúng tôi tạo ra trang web nhằm mục đích mang lại kiến thức bổ ích cho cộng đồng, các bài viết được sưu tầm từ nhiều nguồn trên internet giúp mang lại kiến thức khách quan dành cho bạn

©2022 darkedeneurope.com - Website WordPress vì mục đích cộng đồng

Liên Hệ - Giới Thiệu - Nội Quy - Bảo Mật

No Result
View All Result
  • Trang chủ
  • Chuyên mục
    • Hỏi Đáp
    • Kiến Thức
    • Sức Khỏe
    • Tử Vi
    • Công Nghệ
  • Lưu trữ
  • Liên hệ

© 2022 darkedeneurope.com - Website WordPress vì mục đích cộng đồng.