简单的会话示例不起作用

时间:2015-12-27 16:49:56

标签: php session if-statement

我写了这个小会话脚本,我发现它不起作用。

<?php
  session_start();
  $username = $_SESSION["username"];
?>

  <html><head>
  <title>Simple Session Example</title>
  </head>
  <body>

<?

  if(isset($_SESSION['username'])) {
  $username = $_POST["username"];
  echo "<h3>Hello $username</h3>";
  }

  else {
  echo "<h3>OUT!</h3>"; 
  echo "<form action='index.php' method='POST'>";
  echo "<input type='text' name='username'>";
  echo "<input type='submit' name='submit' value='Submit'></form>";
  }

  ?>

我无法弄清楚哪一部分是错的。看起来对m来说都很好但是肯定是错的。

1 个答案:

答案 0 :(得分:5)

这样的东西?

    <?php
      session_start();
      if(isset($_SESSION['username']))
      $username = $_SESSION["username"];
    ?>

      <html><head>
      <title>Simple Session Example</title>
      </head>
      <body>

    <?

      if(isset($_POST['username'])) {
      $username = $_POST["username"];
      $_SESSION["username"] = $_POST["username"];
      echo "<h3>Hello $username</h3>";
      }

else if($username) {
      echo "<h3>Hello $username</h3>";
      }

      else {
      echo "<h3>OUT!</h3>"; 
      echo "<form action='index.php' method='POST'>";
      echo "<input type='text' name='username'>";
      echo "<input type='submit' name='submit' value='Submit'></form>";
      }

      ?>