检查PHP会话是否存在不起作用

时间:2014-02-09 06:23:06

标签: php session

我正试图找到一种方法来检查是否有会话。如果没有,请重定向回start.php页面。

这些是我制作的页面。

start.php

<form action="form.php" method="post">
    <p>Please enter your name to continue:</p>
    <input type="text" name="name" id="name" />
    <input type="submit" name="enter" id="enter" value="Enter" />
</form>

form.php的

高于head

<?php session_start(); ?>

body

<?php
if(isset($_POST['enter'])){
    if($_POST['name'] != ""){
        $_SESSION['name'] = stripslashes(htmlspecialchars($_POST['name']));
    }
}
$name = $_SESSION['name'];
echo $name;
?>

尝试

我把它放在表格的首部(以及现在的内容)但它只是让我在start.php页面上

<?php 
  if (!isset($_SESSION["name"]))
   {
      header("location: start.php");
   }
   else{
   }
?>

更多信息

所以目前如果没有会话,我输入form.php,它会将我重定向到start.php。但如果有会话,它将保持form.php

但是,如果我从start.php开始并提交表单(创建会话并转移到form.php),它会立即将我重定向回start.php(同一页面)?< / p>

完整的两页代码:

start.php

<?php session_start(); ob_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>

</head>

<body>


    <form action="deletethis.php" method="post">
        <p>Please enter your name to continue:</p>
        <input type="text" name="name" id="name" />
        <input type="submit" name="enter" id="enter" value="Enter" />
    </form>


</body>
</html>

form.php的

<?php 
  session_start();
  if (!isset($_SESSION["name"]))
   {
      //header("location: delete1.php");
      die('<meta http-equiv="refresh" content="0;URL='.'delete1.php'.'" />');
   }
   else{
   }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>

<body>
<?php
if(isset($_POST['enter'])){
    if($_POST['name'] != ""){
        $_SESSION['name'] = stripslashes(htmlspecialchars($_POST['name']));
    }
}
$name = $_SESSION['name'];
echo $name;
?>
</body>
</html>

我决定改为

if (strlen($name) <1){
    echo '<script> window.location.replace("delete1.php");</script>';
    }

1 个答案:

答案 0 :(得分:1)

您需要添加

<?php session_start(); ?>

在最开始的每一页上。

所以,代码应该是这样的

<?php 
  session_start();
  if (!isset($_SESSION["name"]))
   {
      //header("location: delete1.php");
      die('<meta http-equiv="refresh" content="0;URL=\'delete1.php\'" />');
   }
   else{
   }
?>