重定向已登录PHP的用户


Redirect user who already logged in PHP

我想将登录的用户重定向到主页(member index.php),我使用了以下代码来实现这一点,但这不起作用。

<?php
function redirect() {
header('location:member-index.php');
}
 ?> 
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <?php
  if(isset($_SESSION['SESS_FIRST_NAME'])){
   redirect();
  }
?> 
<form id="loginForm" name="loginForm" method="post" action="login-exec.php">
    <input name="email" type="text" class="textfield" id="login" placeholder="username" />
    <input name="password" type="password" class="textfield" id="password" placeholder="password"/>
    <input type="submit" name="Submit" value="LOGIN" />
</form>
</body>
</html>

(login-exec.php)上的会话变量

 $qry="SELECT * FROM members WHERE email='$login' AND passwd='".md5($_POST['password'])."'";
$result=mysql_query($qry);
//Check whether the query was successful or not
if($result) {
    if(mysql_num_rows($result) == 1) {
        //Login Successful
        session_regenerate_id();
        $member = mysql_fetch_assoc($result);
        $_SESSION['SESS_MEMBER_ID'] = $member['member_id'];
        $_SESSION['SESS_FIRST_NAME'] = $member['fullname'];

其他有会话的页面工作得很好,我可以在另一个页面上获取并打印登录用户,但无法在登录表单页面中获取会话工作。。任何帮助都将不胜感激!

我很惊讶错误报告error_reporting(E_ALL); ini_set('display_errors', 1);没有向您发出关于在标头之前输出的警告。

即:

警告:session_start():无法发送会话缓存限制器-标头已发送。。。

<?php session_start(); ?>移动到代码顶部。

<?php session_start(); ?>
<?php
function redirect() {
header('location:member-index.php');
exit;
}
?>

并在标头后添加exit;以避免进一步执行。

还要确保所有文件都不包含字节顺序标记(BOM),并且在页眉之前没有输出。一个空格,HTML,什么都没有,甚至没有cookie,或者任何其他可以作为输出的东西。

  • 所有文件都应该以UTF-8格式保存在代码编辑器中,不带BOM

我在登录表单的顶部添加了这段代码,它成功了!

<?php
      //Start session
      session_start();
  //Check whether the session variable SESS_MEMBER_ID is present or not
  if(isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
    header("location: member-index.php");
    exit();
  }
?>

在文件顶部执行此操作,而不是

<?php
    session_start();
    if(isset($_SESSION['SESS_FIRST_NAME'])){
        header("location: member-index.php");
    } 
?>
<html>....the rest of your html

您可以查看php文档中的header,了解出现问题的原因。以"记住"开头的段落,特别是