简体   繁体   中英

Cookie gets removed before the expire date in PHP

Something really weird, I had this code work before, after about 2weeks i encountered this problem. I have socket chat and on login i set a cookie for about 10 years gets expired, below is how i set it :

   if (!isset($_COOKIE['Token']))
   {
     $user_token  = $user['ID'];
     $token =  md5($user_token,false);
     setcookie("Token",$token,time() + (10 * 365 * 24 * 60 * 60));
   }

Till here it's work fine and getting set on browser and also the expire date is on 2028, So when user try to getting online first he/she will be redirected to index.php to check whether there is any cookie for him set or not in order to log him autimatically with the below code :

session_start();
if(apache_request_headers()['User-Agent'] !== "TEST") die('Access denied');
// $agent = apache_request_headers()['User-Agent'];
// echo put_contents_file("text.txt",$agent);



    if (!isset($_SESSION['LoggedIn_Username']) OR empty($_SESSION['LoggedIn_Username']) OR $_SESSION['LoggedIn_Username'] == NULL OR $_SESSION['LoggedIn_Username'] == "" OR !isset($_COOKIE['Token']))
    {
      if (isset($_COOKIE['Token']))
      {
        $token = $_COOKIE['Token'];
        $sql = mysqli_query($connection,"SELECT Username,ID,TOKEN FROM users WHERE TOKEN='{$token}'");
        $user = mysqli_fetch_array($sql);
        if ($user == true AND $user['TOKEN'] == $token)
        {
          $_SESSION['LoggedIn_Username'] = $user['Username'];
          $_SESSION['My_ID'] = $user['ID'];
          Header('Location: profile.php');
        }else
        {
          Header('Location: logout.php');
        }
      }else
      {
        Header('Location: logout.php');
      }
    }else
    {
      Header('Location: profile.php');
    }

Above code will see if the user agent was TEST it will allow users to enter, else it will not. After being allowed it will see if the required sessions exist or not,if not then cookie should help and finding the token from database and set session for him again,if cookie and sessions was not set it will redirect to logout.php , But after 2 hours only this cookie Token gets removed and i don't know really why this happen, Any idea?

Note: My cookie was UserToken before after i got into this problem i changed it's name to Token

因此,问题在于与数据库的连接,但未成功...

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