简体   繁体   中英

php login with cookies and sessions

I want to get a simple login form, for signed users it must say "Hello, login", but cookies are not working and it's always like I'm not signed in. Please help what am I doing wrong?
this is my html file:

<form action="index.php" method="post">
    <input type="text" name="login"/>
    <input type="password" name="password"/>
    <input type="submit" value="LOGIN"/>
</form>

and php:

 <?php
        session_start(); 
        $login = $_POST['login'];
        $password = $_POST['password'];

        function getUsers()
        {
            return array('test'=>'123','jack'=>'345');
        }

        function checkLoginPassword($login, $password)
        {
            $users=getUsers();
            if(!isset($users[$login]))
                return false;
            if($users[$login] != $password)
                return false;
            return true;
        }

        function login($login,$password)
        {
            if(!checkLoginPassword($login,$password)) {
                return false;
            }
            $id = rand(1,100);
            setcookie('user_session',$id,time()+86400);
            $_SESSION['user_'.$id]=$login;
        }

        function isLoggedIn()
        {
            if(!isset($_COOKIE['user_session']))
                return false;
            $id=(int)$_COOKIE['user_session'];
            if(!isset($_SESSION['user_'.$id]))
                return false;
            return true;
        }

        if (isLoggedIn()){
            echo "Hello, ".$login; 
        }
        else echo "You are not signed in!";
function isLoggedIn()
{
    if(!isset($_COOKIE['user_session']))
        return false;
    $id=(int)$_COOKIE['user_session'];
    if(!isset($_SESSION['user_'.$id]))
        return false;
    return true;
}

this solution is bad, but to actually answer your question, the issue is $id is not set here. there is no local, nor global $id

Even when you press login in html in php is this function not mentioned at all.

You need to put this in your code and than it will work.

if (!empty($_POST)) {
    $login = $_POST['login'];
    $password = $_POST['password'];

    login($login, $password);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM