且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 PHP 中使用登录 cookie 连接用户?

更新时间:2021-06-29 20:15:06

PHP 中的登录脚本可以使用 会话.

A login script in PHP can be implemented using sessions.

简单来说,会话​​是唯一的,并且只要页面打开(或直到它超时)就一直存在.如果您的浏览器已关闭,会话也会发生同样的情况.

Making it simple, sessions are unique and lives as long as the page is open (or until it timeouts). If your browser is closed, the same happens to the session.

它们实施起来非常简单.首先,确保在每个页面的开头开始会话:

They are pretty simple to implement. First, make sure you start sessions at the beginning of each page:

<?php session_start(); ?>

注意:此调用出现在任何页面输出之前很重要,否则会导致标题已发送"错误.

Note: It's important that this call comes before of any page output, or it will result in an "headers already sent" error.

好的,现在您的会话已启动并正在运行.接下来做什么?这很简单:用户通过登录表单发送其登录名/密码,然后您对其进行验证.如果登录有效,则将其存储到会话中:

Alright, now your session is up and running. What to do next? It's quite simple: user sends it's login/password through login form, and you validate it. If the login is valid, store it to the session:

if($validLoginCredentials){
    $_SESSION['user_id'] = $id;
    $_SESSION['user_login'] = $login;
    $_SESSION['user_name'] = $name;
}

或作为数组(我更喜欢):

or as an array (which I prefer):

if($validLoginCredentials){
    $_SESSION['user'] = array(
        'name' => $name,
        'login' => 'login',
        'whichever_more' => $informationYouNeedToStore
    );
}

好的,现在你的用户已经登录了.那么你怎么知道/检查呢?只需检查用户的会话是否存在.

Ok, now your user is logged in. So how can you know/check that? Just check if the session of an user exists.

if(isset($_SESSION['user_id'])){ // OR isset($_SESSION['user']), if array
// Logged In
}else{
// Not logged in :(
}

当然你可以更进一步,除了检查会话是否存在,在数据库中搜索会话存储的用户 ID 来验证用户.这完全取决于您需要多少安全性.

Of course you could go further, and besides of checking if the session exists, search for the session-stored user ID in the database to validate the user. It all depends on the how much security you need.

在最简单的应用程序中,永远不会存在 $_SESSION['user'] 除非您在登录操作中手动设置它.因此,只需检查它是否存在即可告诉您用户是否已登录.

In the simplest application, there will never exist a $_SESSION['user'] unless you set it manually in the login action. So, simply checking for it's existence tells you whether the user is logged in or not.

注销:只需销毁它.你可以使用

Loggin out: just destroy it. You could use

session_destroy();

但请记住,这会破坏您为该用户设置的所有会话.如果您还使用了 $_SESSION['foo'] 和 $_SESSION['bar'],它们也会消失.在这种情况下,只需取消设置特定会话:

But keep in mind that this will destroy all sessions you have set up for that user. If you also used $_SESSION['foo'] and $_SESSION['bar'], those will be gone as well. In this case, just unset the specific session:

unset($_SESSION['user']);

大功告成!用户不再登录!:)

And done! User is not logged in anymore! :)

嗯,就是这样.再次提醒您,这些是非常简单的登录方法示例.您需要多研究一点,并根据应用程序的安全要求,通过更多层的安全检查来改进代码.

Well, that's it. To remind you again, these are very simple login methods examples. You'll need to study a bit more and improve your code with some more layers of security checks depending on the security requirements of your application.