Search code examples
phpsmarty

Smarty Login with Session - needs page refresh to see in templates


I have a small web application with smarty template engine. The login is in the header.tpl. Login & Logout are working fine, but they need a page reload to see the changes in the header. Any ideas why this happens? I think there is no caching activated.

header.tpl

{if isset($user) }
   <form class="logoutform col-md-12 nopadding" method="post">
      <div class="col-md-10"><p class="welcometext">Hello {$user.username}!</p></div>
      <div class="hidden"><input type="hidden" name="action" value="logout"></div>
      <div class="col-md-2"><button type="submit">Logout</button></div>
   </form>
{else}
   <form class="loginform col-md-12 nopadding" method="post">
      <div class="col-md-5"><input type="text" placeholder="Username" name="username"></div>
      <div class="col-md-5"><input type="password" placeholder="Password" name="password"></div>
      <div class="hidden">
         <input type="hidden" name="action" value="login">
      </div>
      <div class="col-md-2"><button type="submit">Login</button></div>
   </form>
{/if} 

function login & logout in der page.class.php

function logout()
{
    session_destroy();
    //header('Location: '.BASEURL);
}
function login($username, $password)
{          
      $pdo = new PDO('mysql:host='.HOST.';dbname='.DATABASE, USER, PASSWORD);

      $statement = $pdo->prepare("SELECT * FROM users WHERE username = :username");
      $result = $statement->execute(array('username' => $username));
      $user = $statement->fetch(PDO::FETCH_ASSOC);
      //DB Abfrage in user class exportieren? checkUserLogin, dann return true oder errormeldung

      if ($user == false || password_verify($password, $user['password']) == false) {
         $loginerror = 'username or password wrong';
      }
      else {

         if ($user['email_confirmed']==0) {
            //$this->assign('error', 'Please confirm your e-mail adress.');
            $loginerror = 'please confirm your e-mail adress.';            
         }
         else {
            //$_SESSION['loggedUser'] = $user['id'];
            $_SESSION['user'] = $user;
            return true;
         }
      }
      $this->assign('loginerror', $loginerror);
   }
} 

Solution

  • Yes, as any web application on server side. You have to do a redirect at the end of the login, something like header('Location: '.$yourLoginPageUrl); to force the refresh.