title: Checking if user already logged in, cookie check
body: <p>I am having an issue with something I have already posted but I thought I would ask the problem again as I have more code with it now.</p>
  
  <p>The ORIGINAL code that I  have used for the tutorial</p>
  
  <pre><code>function checkLoggedIn($page)
  {
     $loginDiv = '';
     $action = '';
     if (isset($_POST['action']))
     {
        $action = stripslashes ($_POST['action']);
     }
  
     session_start ();
  
     // Check if we're already logged in, and check session information against cookies
     // credentials to protect against session hijacking
     if (isset ($_COOKIE['project-name']['userID']) &amp;&amp;
         crypt($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'],
               $_COOKIE['project-name']['secondDigest']) ==
         $_COOKIE['project-name']['secondDigest'] &amp;&amp;
         (!isset ($_COOKIE['project-name']['username']) ||
          (isset ($_COOKIE['project-name']['username']) &amp;&amp;
           Users::checkCredentials($_COOKIE['project-name']['username'],
                                   $_COOKIE['project-name']['digest']))))
     {
        // Regenerate the ID to prevent session fixation
        session_regenerate_id ();
  
        // Restore the session variables, if they don't exist
        if (!isset ($_SESSION['project-name']['userID']))
        {
           $_SESSION['project-name']['userID'] = $_COOKIE['project-name']['userID'];
        }
  
        // Only redirect us if we're not already on a secured page and are not
        // receiving a logout request
        if (!isSecuredPage ($page) &amp;&amp;
            $action != 'logout')
        {
           header ('Location: ./');
  
           exit;
        }
     }
     else
     {
        // If we're not already the login page, redirect us to the login page
        if ($page != Page::LOGIN)
        {
           header ('Location: login.php');
  
           exit;
        }
     }
  
     // If we're not already logged in, check if we're trying to login or logout
     if ($page == Page::LOGIN &amp;&amp; $action != '')
     {
        switch ($action)
        {
           case 'login':
           {
              $userData = Users::checkCredentials (stripslashes ($_POST['login-username']),
                                                   stripslashes ($_POST['password']));
              if ($userData[0] != 0)
              {
                 $_SESSION['project-name']['userID'] = $userData[0];
                 $_SESSION['project-name']['ip'] = $_SERVER['REMOTE_ADDR'];
                 $_SESSION['project-name']['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
                 if (isset ($_POST['remember']))
                 {
                    // We set a cookie if the user wants to remain logged in after the
                    // browser is closed
                    // This will leave the user logged in for 168 hours, or one week
                    setcookie('project-name[userID]', $userData[0], time () + (3600 * 168));
                    setcookie('project-name[username]',
                    $userData[1], time () + (3600 * 168));
                    setcookie('project-name[digest]', $userData[2], time () + (3600 * 168));
                    setcookie('project-name[secondDigest]',
                    DatabaseHelpers::blowfishCrypt($_SERVER['REMOTE_ADDR'] .
                                                   $_SERVER['HTTP_USER_AGENT'], 10), time () + (3600 * 168));
                 }
                 else
                 {
                    setcookie('project-name[userID]', $userData[0], false);
                    setcookie('project-name[username]', '', false);
                    setcookie('project-name[digest]', '', false);
                    setcookie('project-name[secondDigest]',
                    DatabaseHelpers::blowfishCrypt($_SERVER['REMOTE_ADDR'] .
                                                   $_SERVER['HTTP_USER_AGENT'], 10), time () + (3600 * 168));
                 }
  
                 header ('Location: ./');
  
                 exit;
              }
              else
              {
                 $loginDiv = '&lt;div id="login-box" class="error"&gt;The username or password ' .
                             'you entered is incorrect.&lt;/div&gt;';
              }
              break;
           }
           // Destroy the session if we received a logout or don't know the action received
           case 'logout':
           default:
           {
  
              // Destroy all session and cookie variables
              $_SESSION = array ();
              setcookie('project-name[userID]', '', time () - (3600 * 168));
              setcookie('project-name[username]', '', time () - (3600 * 168));
              setcookie('project-name[digest]', '', time () - (3600 * 168));
              setcookie('project-name[secondDigest]', '', time () - (3600 * 168));
  
              // Destory the session
              session_destroy ();
  
              $loginDiv = '&lt;div id="login-box" class="info"&gt;Thank you. Come again!&lt;/div&gt;';
  
              break;
           }
        }
     }
  
     return $loginDiv;
  }
  </code></pre>
  
  <p>My code: </p>
  
  <pre><code>&lt;?php
  
  function encrypt($input)
  {
  $hash = password_hash($input, PASSWORD_DEFAULT);
  return $hash;
  }
  
  function checkUserCreds($username, $password)
  {
      $id = 0;
      $hash = '';
  
      $db = new PDO('$dbDNS', '$dbuser', '$dbpass');
      $db-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Set error mode
      try
      {
          $st = $db-&gt;prepare("SELECT id, login, email, pass FROM users WHERE login =:username");      
          $st-&gt;bindParam(':username', $username, PDO::PARAM_STR);
          $success = $st-&gt;execute();
  
          if($success)
          {
              $userData = $st-&gt;fetch();
              $hash = $userData['pass'];
              if (password_verify($password, $hash) == $hash)
              {
                  $id = $userData['id'];
              }           
          }
  
      }
      catch (PDOException $e)
      {
          $id = 0;
          $hash = '';
      }
      $db = null;
  
      return array ($id, $username, $hash);
  }
  
  function checkLoggedIn($page)
  {
      $loginMess='';
      $action='';
      if (isset($_POST['action']))
      {
          $action = stripslashes($_POST['action']);
      }
      session_start();
  
      //Check if already logged in and check session information against cookies
      if (isset($_COOKIE['sukd']['id']) &amp;&amp; encrypt($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']) == $_COOKIE['sukd']['hashv2'] &amp;&amp; (!isset ($_COOKIE['sukd']['username']) || (isset ($_COOKIE['sukd']['username']) &amp;&amp; checkUserCreds($_COOKIE['sukd']['username'], $_COOKIE['sukd']['hash']))))
      {
          echo "isset cookies: ON, GOOD &lt;br&gt;";
          // Regenerate the ID to prevent session fixation
          //session_regenerate_id ();
      }   
      else
      {
          // If we are not on the login page, redirect.
          if ($page != 'login')
          {
              header ('Location login.php');
              exit;
          }
      }
      if ($page = 'login' &amp;&amp; $action != '')
      {
          switch($action)
          {
              case 'login':
              {
                  $userData = checkUserCreds(stripslashes($_POST['username']), stripslashes($_POST['password']));
  
                  if ($userData[0] != 0)
                  {
                      $_SESSION['sukd']['id']=$userData[0];
                      $_SESSION['sukd']['ip']=$_SERVER['REMOTE_ADDR'];
                      $_SESSION['sukd']['userAgent']=$_SERVER['HTTP_USER_AGENT'];
                      if(isset($_POST['remember']))
                      {
                          //remember for 7 days
                          setcookie('sukd[id]', $userData[0], time () + (3600 * 168));
                          setcookie('sukd[username]', $userData[1], time() + (3600 * 168));
                          setcookie('sukd[hash]', $userData[2], time() + (3600 * 168));
                          setcookie('sukd[hashv2]', encrypt($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']), time () + (3600 * 168));
                      }
                      else
                      {
                          setcookie('sukd[id]', $userData[0], false);
                          setcookie('sukd[username]', '', false);
                          setcookie('sukd[hash]', '', false);
                          setcookie('sukd[hashv2]', encrypt($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']), time () + (3600 * 168));
                      }
  
                      header ('Location: ./');
  
                      exit;
                  }
                  else
                  {
                      $loginMess = "The username or password you entered is incorrect &lt;br&gt;";
                  }
                  break;              
              }
              case 'logout':
              default:
              {
                  $_SESSION = array();
                  setcookie('sukd[id]', '', time () + (3600 * 168));
                  setcookie('sukd[username]', '', time() + (3600 * 168));
                  setcookie('sukd[hash]', '', time() + (3600 * 168));
                  setcookie('sukd[hashv2]', '', time () + (3600 * 168));
  
                  session_destroy();
  
                  $loginMess = "echo 'Successfully logged out &lt;br&gt;'";
  
                  break;          
              }       
          }
      }
      return $loginMess;
  }
  ?&gt;
  </code></pre>
  
  <p>It is called by <code>checkLogged(login)</code> for example and that outputs the login message if there is a problem. In addition it uses a hidden field with action to set the value, login or logout for the case switch. Currently, it logs in fine, adds the cookies etc.</p>
  
  <p>However, the problem is, when a user has already logged in, it should be checking the code.</p>
  
  <pre><code>if (isset($_COOKIE['sukd']['id']) &amp;&amp; encrypt($_SERVER['REMOTE_ADDR'] etc..
  </code></pre>
  
  <p>I couldn't really make much sense of the original code, so I am not even sure where to begin. The cookie array is a bit weird how it seems to be based on two different versions based on whether you setcookie or call the cookie.</p>
  
  <p>If anyone has a more secure without going over the top method, I am happy for someone to enlighten me further on this.</p>
  
  <p>Original to my code.</p>
  
  <pre><code>digest = hash
  decondDigest = hashv2
  </code></pre>