1

I ask for help to you, I explain my problem. In my User () class, I wrote a small function to log in, then recording sessions and setting cookies.

Here it is:

public function login($username, $password) {   
    $this->db->query("SELECT * FROM users WHERE username = :username AND status = :status LIMIT 1");
    $this->db->bind(':username', $username);
    $this->db->bind(':status', 1);
    $row = $this->db->single();
    $count = $this->db->rowCount();
        if ($count > 0) {
            if (password_verify($password, $row['password'])) {
                $this->setSession($row);
                return true;
            } else {
                return false;
            }
        }
}

public function setSession($row) {
    $_SESSION['session'] = [
        'id' => $row['id'],
        'username' => $row['username'],
        'email' => $row['email']
    ];
    //set cookie
    setcookie("name_cookie", md5($_SESSION['session']['username']/$_SESSION['session']['password']), time()+3600 * 24 * 365);
}

And here is the function to check if the user is connected or not, to protect the pages:

public function isLoggedIn() {
    if(isset($_SESSION['session'])) {
        return true;
    }
    return false;
}

My problem would be that even if cookies are set, unfortunately the session after a total time expires.

I set the cookies to a year, but as I said, the user's login session expires after a while. How can I correct this?

1 Answers1

0

PHP sessions expire at the server level. The default is around 20 minutes, and you can control this in your php.ini settings.

You could use setcookie to save a cookie to the user's browser, and then check it using the $_COOKIE variable in PHP. See setcookie.

But be aware of the security risks with this. Anyone can steal the cookie and then get access to the site as that user. Some good ideas for securing your cookie can be found here.

Community
  • 1
  • 1
  • Hello, I wanted to make these changes because it is unfamiliar believe, however, was a more secure method to protect pages. – Marco Bonanno May 17 '16 at 18:58
  • At this time, my class can exceed minimum safety requirements? I know that is not the top, but be sure the minimum? @Andreas Huttenrauch – Marco Bonanno May 18 '16 at 07:22
  • I would recommend at minimum: (1) Generate unique hashes for each customer and save only the hash in the cookie, and (2) When you use a cookie to create a login, change the hash value so it can't be used again – Andreas Huttenrauch May 18 '16 at 15:44
  • I know I'm asking a lot, but could you give me an example in my code posted earlier? I am not very experienced, especially for this thing. If I understand it, I create a tag with a unique code per user called, say, $hashcode. I put $hashcode of setcookie of value, by replacing ($ _ SESSION ['session'] etc etc. How can I make $ hashcode? md5 okay? For the rest as continuous? Thanks for your help. – Marco Bonanno May 19 '16 at 07:47