可以';t从SESSION获取变量


Can't get variables from SESSION

我的学校项目有问题。我向老师和同学们寻求帮助,但他们都不知道该怎么办

我制作了一款基于浏览器的游戏,显然它需要用户。这就是问题所在。

当我登录并进入身份验证页面时,它从POST中提取信息很好,但当我在身份验证中将信息插入SESSION,然后转到主页索引时,它拒绝获取SESSION信息,我只是收到了一个错误。

注意,design2.php与登录过程没有任何关系。

这是代码:

Login.php

<?php
include_once'design2.php';
?>
<div id="center">
<form method="POST" action="authenticate.php">
User Name <input id="input" type="text" name="player" size="21">
Password <input id="input" type="password" name="password" size="21">
<br>
<input type="submit" value="Login" name="submit">
<br><br>Not Registered? <a id='underlinelink' href='register.php'>Register</a>

Authenticate.php

<?php
include_once 'connect.php';
?>
<div id="center">
<?php
if (isset($_POST['submit']))
{
  $player=$_POST['player'];
  $password=$_POST['password'];
  $player=strip_tags($player);
  $password=strip_tags($password);
  $password=md5($password);
  $query = "select name, password from players where name='$player' and password='$password'";
  $result = mysql_query($query) or die("Could not query players");
  $result2 = mysql_fetch_array($result);
  if ($result2)
  { 
    $_SESSION['player'] = $player;
    echo "<big>Logged in successfully<br>";
    echo "<A id='underlinelink' href='index.php'>Continue</a></big>";
  }
  else
  {
   echo "<big>Wrong username or password.<A id='underlinelink' href='login.php'>Try Again</a></big>";
  }
}
?>
</div>

Design.php(这是我网站上的每一个网页(

<?php
include_once 'connect.php';
?>
<link href="stilark.css" rel="stylesheet" type="css" />
<?php
session_start();  
if(isset($_SESSION['player']))
    $player = $_SESSION['player'];
else
    echo "could not logg in, <a href='login.php'>Go back</a>"; 
    exit;
$playerinfo="SELECT * from players where name='$player'";
$playerinfo2=mysql_query($playerinfo) or die("could not get player stats!");
$playerinfo3=mysql_fetch_array($playerinfo2);
?>

请帮忙,我真的需要在到期之前完成这件事。

在写入会话之前,您需要创建或恢复会话。因此,在执行$_SESSION['player'] = $player;Authenticate.php中,首先创建一个会话,就像在其他文件中一样。类似的东西

Authenticate.php

<?php
session_start();
include_once 'connect.php';
?>
<div id="center">
<?php
// Rest of your code
// ...
if ($result2)
{ 
    $_SESSION['player'] = $player;
// and so on...

此外,正如@DamienLegros在他的回答中指出的那样,您应该始终在代码中尽早使用session_start()语句,即作为第一个语句之一,这样您就可以确保在它启动之前没有进行任何输出。否则,您将开始收到声明headers has already been sent的错误。

您的session_start()必须在任何输出之前

<?php
session_start(); 
include_once 'connect.php';
?>
<link href="stilark.css" rel="stylesheet" type="css" />
<?php
session_start();
include_once 'connect.php';
?>
<div id="center">
<?php
if (isset($_POST['submit']))
...
...
...

注意:在Authenticate.php页面的顶部添加session_start();