That’s the first big question I see. In most cases, you should use sessions. There are some exceptions, but it’s usually very specific cases and at the far end of “complex” if/when you do it. Why? Session data is stored on the server and therefore is, in general, safer to work with.

Đang xem: Php session login and logout

Whereas, cookies are stored in the browser…

And, it’s the Wild West out there, partna!

Okay, that outta the way… let’s get into how to do this.

I just went through all this in recording my latest course, How to Create a Login Script, and always do a bunch of research to make sure I’m up to date on the latest and greatest in whatever topic.

So, the basic idea is this:

User submits login formPassword is verifiedCreate a session variableCheck session variable on every page loadDestroy session on logout

Okay, let’s look at some code.

Xem thêm: Các Thẻ In Đậm Trong Html /Thẻ Lệnh/Kiểu Chữ, Định Dạng Trong Html

Login Form

Nothing special here, really. A simple form that includes username and password fields. Action parameter is left blank assuming this form submits to itself. Of course, change that if you have a processing script at a different URL that you want to use.

Process Login

Here, we do a couple things. First, we look for and grab the user data from the database based on the username submitted. Then, we verify the password submitted against the password hash stored in our database using password_verify(). Finally, we create the user session if the password is correct. It’s this session variable we’ll check on each page load going forward.

prepare(“SELECT * FROM users WHERE username = ?”); $stmt->bind_param(“s”, $_POST<"username">); $stmt->execute(); $result = $stmt->get_result(); $user = $result->fetch_object(); // Verify user password and set $_SESSION if ( password_verify( $_POST<"password">, $user->password ) ) { $_SESSION<"user_id"> = $user->ID; } }}?>

Page

Any pages you want to “protect”, you’d want to check for the required $_SESSION variable. This is a simple example of how to do that.

Xem thêm: Căn Bệnh Thiếu Hơi Đàn Ông Ở Phụ Nữ Lại Dễ Bị Mất Ngủ? Có Thật Không

Logout

Logout is pretty straight-forward. We just destroy the session, so now the $_SESSION variable won’t exist and users will be directed to log in again. Keep in mind, this also happens whenever the browser is closed because we’re using sessions.

So, that’s the basic nuts and bolts of creating a login system using PHP sessions. If you want to keep going with this tutorial, you can on my free tutorial site here: https://johnsfreetuts.com/logintut/

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *