会话php不工作

时间:2015-07-26 11:22:08

标签: php session

我使用会话构建了一个Admin-login,但它不起作用,它要求我再次登录。它无法识别会话。

怎么了?

<!DOCTYPE HTML>
<html>
<head>
<?php
session_start();
include "../header.php";
echo $_SESSION['username'];
?>
<title></title>
</head>
<body dir="rtl">
<?php if(!isset($_SESSION['username'])) { ?>
<h1>כניסה לפאנל ניהול</h1>
<form action="index.php" method="post">
     <input name="adminName" placeholder="שם משתמש">
     <br>
     <input name="adminPass" placeholder="סיסמה">
     <br>
     <input type="submit" name="login" value="כניסה" class="btn btn-primary">
     </form>
     <br>
     <?php
     $username = $_POST['adminName'];
     $password = $_POST['adminPass'];

     if(isset($_POST['login'])) {
         $connect_db = mysql_connect("X", "X", "X");
         $select_db = mysql_select_db("X");
         $login_query = mysql_query("SELECT * FROM `X`.`admin_login` WHERE `Username` = '$username' and `Password` = '$password';");
         $login_num = mysql_num_rows($login_query);
         if($login_num == 1) {
             $da = mysql_query("SELECT * FROM `X`.`admin_login` WHERE `Username` = '".$_SESSION['username']."'");
             while($row = mysql_fetch_array($da)) {
                 $_SESSION['username'] = $username;
                 $_SESSION['name'] = $row['Name'];
                 $_SESSION['date'] = $row['Date'];
             }
             echo '<div class="alert alert-success">
                   <strong>הצלחה!</strong> התחברת בהצלחה לפנאל ניהול! <a href="index.php">רענן</a>
                 </div>';
         }
         else {
             echo '<div class="alert alert-warning">
                   <strong>שגיאה:</strong> שם המשתמש או הסיסמה אינם נכונים
                 </div>';
         }
     }
}
else if(isset($_SESSION['username'])) {
    echo 'ברוך הבא, '.$_SESSION['username'];
}
?>
<br>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您需要将session_start()放在产生输出的任何内容之前。因此,将脚本的开头更改为:

<?php 
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<?php
include "../header.php";

请参阅How to fix "Headers already sent" error in PHP