PHP - 如何让我的用户保持登录状态?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20585405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:19:18  来源:igfitidea点击:

PHP - How can i keep my user logged in?

phpsession

提问by user2744048

I'm using a function for login.

我正在使用登录功能。

But when i change the page from my website, i have to login again.

但是当我从我的网站更改页面时,我必须再次登录。

how can i keep my user logged in when i change my page?

当我更改我的页面时,如何让我的用户保持登录状态?

Here my code:

这是我的代码:

<?php
error_reporting(0);
if($_POST['login']=="") {
?>
  <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
    <label><a>Utilizador</a><input type="text" name="login" id="s-user"></label>
    <label><a>Senha</a><input type="text" name="password" id="s-pass"></label>
      <input type="submit" class="submit" value="Entrar">

  </form>


<?php
}
else {
?>
<?php
include("classes/Utilizadores/Cliente.class.php");


        if($_REQUEST['login']!="") {
            if($_REQUEST['password']!="") {

                            $clientes = new Cliente();
                            if($clientes->verificarCliente($_REQUEST['login'], $_REQUEST['password'])) {
                                echo "<br>";
                            } else {
                                echo "<br><a>Login ou senha errados, caso n?o tenha, <a href='criarconta.php'> registre-se</a>, <a>ou</a> <a href='index.php'>volte a tentar.</a></a><br>";
                            }
                            $clientes->endCliente();

            } else {
                echo "ERRO: Deve introduzir a sua password...<br>";
            }
        } else {
            echo "ERRO: Deve introduzir o seu login...<br>";
        }

}
?>

My function code:

我的功能代码:

function verificarCliente($login, $password) {
    $sql = "SELECT * FROM users WHERE login LIKE '$login' AND password LIKE '$password'";
    if(($rs=$this->bd->executarSQL($sql))){
        if(mysql_fetch_row($rs)==false) {
            return false;
        } else {

                                echo "<br><b> <a>Bem-Vindo <font size=2>" .mysql_result($rs,0,"login")."</font></b></a><br><br><br>";     

            return true;

        }
    }
    else {
        return false;
    }
}

采纳答案by robbmj

First off I would highly recommend not using the LIKE operator, use the = operator instead. Also I would recommend using parametrized quires. Also I would recommend hashing your user's passwords, salting them is a very good idea too.

首先,我强烈建议不要使用 LIKE 运算符,而是使用 = 运算符。我也建议使用参数化的查询。此外,我建议对用户的密码进行哈希处理,对它们进行加盐处理也是一个非常好的主意。

Give these pages a read. There is good information here:

阅读这些页面。这里有很好的信息:

How can I prevent SQL injection in PHP?

如何防止 PHP 中的 SQL 注入?

Secure hash and salt for PHP passwords

PHP 密码的安全散列和盐

crackstation.netsupplies a free library for multiple languages and a good explanation.

rackstation.net提供了一个免费的多语言库和一个很好的解释。

But you need to keep track of the logged in user:

但是您需要跟踪登录的用户:

function verificarCliente($login, $password) {

        $sql = "SELECT * FROM users WHERE login = '$login' AND password = '$password'";
        if(($rs=$this->bd->executarSQL($sql))){
            if(mysql_fetch_row($rs)==false) {
                return false;
            } else {
                session_start();
                $the_username = // grab the username from your results set  
                $_SESSION['username'] = $the_username; 

                // put other things in the session if you like
                echo "<br><b> <a>Bem-Vindo <font size=2>" .mysql_result($rs,0,"login")."</font></b></a><br><br><br>";     

                return true;

            }
        }
        else {
            return false;
        }
    }

Now on other pages that require a user to be logged in

现在在需要用户登录的其他页面上

session_start();
if (!isset($_SESSION['username']) || empty($_SESSION['username'])) {
      // redirect to your login page
      exit();
}

$username = $_SESSION['username'];
// serve the page normally.

回答by Eisa Adil

Use $_SESSIONVariables. http://www.php.net/manual/en/reserved.variables.session.php. They help you store variables you can access them from any other part of the website.

使用$_SESSION变量。http://www.php.net/manual/en/reserved.variables.session.php。它们帮助您存储变量,您可以从网站的任何其他部分访问它们。

On login success:

登录成功时:

1) Query basic info like first name, last name, sex, birthday etc.

1) 查询基本信息,如名字、姓氏、性别、生日等。

2) Save them in variables such as $first_name, $last_name etc.

2) 将它们保存在 $first_name、$last_name 等变量中。

3) Assign those variables to sessions like this:

3)将这些变量分配给这样的会话:

$first_name = $_SESSION['first_name'];
$birthday = $_SESSION['birthday'];

On logout, simply destroy the session with session_destroy().

注销时,只需使用 session_destroy() 销毁会话。

So $_SESSION['first_name']would be the first name of the user that can be manipulated from anywhere on the code.

因此,$_SESSION['first_name']将可以从代码的任何地方进行操作的用户的名字。

EDIT: I quoted php.net instead of W3 school because a lot of people don't seem to like it.

编辑:我引用了 php.net 而不是 W3 school 因为很多人似乎不喜欢它。

回答by Asad Malik

You are not saving the state of a user. You should save the state of a user in a session and retrieve on the next page.

您不是在保存用户的状态。您应该在会话中保存用户的状态并在下一页检索。

Please review http://www.w3schools.com/php/php_sessions.asp

请查看http://www.w3schools.com/php/php_sessions.asp