会话不在一个PHP页面上工作

时间:2012-07-01 21:31:40

标签: php session

此登录脚本有什么问题?我有一个模态式iframe登录框,/login.php我有一个/index.php

登录后,login.php会重定向到index.php,但我看不到用户名。只是Hello Guest。当我尝试登录时,you, username, are already logged in说。

的login.php:

<?php session_start(); require_once('connections/Main.php');

if(isset($_SESSION['username'])) {

    echo '<div class="error_message">Attention! You, '.$_SESSION['username'].' are already logged in.</div>';
    echo "<br />";
    echo "Go <a href='javascript:history.go(-1)'>back</a> to the page you were viewing before this.</li>";

    exit();
}
?>

的index.php:

<?php session_start(); 
   require_once('connections/Main.php'); 
     ?>

<div> Hello <?php   if(isset($_SESSION['username'])) { 
          echo $_SESSION['username']; }
                    else{ echo 'Guest'; } ?></div>

2 个答案:

答案 0 :(得分:0)

您正在拨打session_start()两次,这是不必要的。登录后,请将会话变量logged_in设置为true。然后使用

if($_SESSION['logged_in']){
 //Do what you want for the logged in user
}

说实话,你可以在一个login.php中完成所有这些。有这样的事情:

//if reached from login form
if ($_POST['email']){
  //validate the user
  // if validates, log him in by:
    $_SESSION['logged_in'] = true;
    $_SESSION['email']= $_POST['email'];
  //do other fancy database save stuff
 }
//else show him login form
else{
  <form>
   //<input />.. etc
  </form>
}

答案 1 :(得分:-2)

以此开始您的会话。

$_SESSION["im_going_in"]=true; 
$_SESSION["username"]=$username;//get data from db.

<强>的index.php

<?php
if($_SESSION["im_going_in"]) {
?>

  <?=strtoupper($_SESSION["username"])?>// welcome dear bla bla...

<?
}
?>