Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Cookie vs Session variables

I am modifying a login script from php-login.net and trying to make it more secure. This particular login script has a login class that sets both cookie and session variables when the user logs in.

/**
 *  write user data into PHP SESSION [a file on your server]
 */
   $_SESSION['user_name'] = $result_row->user_name;
   $_SESSION['user_email'] = $result_row->user_email;
   $_SESSION['user_logged_in'] = 1;

/**
 *  write user data into COOKIE [a file in user's browser]
 */
   setcookie("user_name", $result_row->user_name, time() + (3600*24*100));
   setcookie("user_email", $result_row->user_email, time() + (3600*24*100));
   $this->user_is_logged_in = true;

The unfortunate part is that on the page the user gains access to, nobody wrote a check to make sure the user was logged in when they got to that page. So if a person just types in the URL directly, they would not have to be logged in.

I want to know the best way to verify that the user has logged in. Currently, I am using this, but I do not know if it is redundant (meaning: will cookie variables always equal session variables, so there is no point in checking both?) Any input would be helpful.

session_start();
if(!(isset($_COOKIE['user_email']) && 
    isset($_SESSION['user_email']) &&
    ($_COOKIE['user_email']===$_SESSION['user_email']) &&
    isset($_COOKIE['user_name']) && 
    isset($_SESSION['user_name']) && 
    ($_COOKIE['user_name']===$_SESSION['user_name']) && 
    isset($login) && 
    $login->isUserLoggedIn())){
        header("location:../../index.php");
        exit;
     }

(Sorry for the poorly formatted code, I am still trying to figure out the nuances of text formatting on this site)

like image 494
Scott Avatar asked Mar 10 '26 04:03

Scott


1 Answers

When using sessions there is already a cookie present with the session id which maps to a server side php session. All data you register there will be available in the global $_SESSION array. Storing the data in both the cookie aswell as on the server is normally pointless.

Only reason you would store the data in the cookie aswell is if you have more sites on the same domain name that need to share the cookie data.

like image 193
Damien Overeem Avatar answered Mar 12 '26 18:03

Damien Overeem