PHP $ _POST数组空

时间:2016-10-07 17:57:21

标签: php arrays session

我是编码新手,在Mac上编码时出现问题。

当我做var_dump($ _ POST)时,回答是:array(0){}

以下是代码:

<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name=strip_tags($_POST["name"]);
    $age=$_POST["age"]*1;
    $_SESSION["name"] = $name;
    $_SESSION["age"] = $age;
}
else {
    $name = $_SESSION["name"];
    $age = $_SESSION["age"];
}

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title>Session demonstration</title>
</head>

<body>
<h1>Session demonstration</h1>
<a href="session-2.php">Demo session</a><br>
<a href="session_destroy.php">Close session</a><br><br>
<form action="<?=$_SERVER["PHP_SELF"]?>"
      method="post">
    Your name is:
    <input type="text" name="name" value="<?php echo $name?>"><br>
    You are:
    <input type="text" name="age" value="<?php echo $age?>"><br>
    <input type="submit" value="Submit">
</form>
<?php
if ($name and $age) {   
    if ($name and $age) {
        echo "<h1>Hello, $name</h1>";
        echo "<h3>You are $age</h3>";
    }
    else {
        print "<h3>Bye!</h3>";
    }
}
?>
</body>
</html>

同时,当我按下提交按钮时,它会显示我:

注意:未定义的索引:第5行的/ Applications / MAMP / htdocs / PHP_Course 2 / demo / mod2 / sessions / session-1.php中的名称

注意:未定义的索引:年龄在/ Applications / MAMP / htdocs / PHP_Course 2 / demo / mod2 / sessions / session-1.php第6行

也许有人知道我能做些什么。

Sincerelly

1 个答案:

答案 0 :(得分:0)

这个问题是你的会话变量没有在开头设置,而你试图在你的else块上为你的$ name和$ age分配这些未分配的变量。像这样验证你的作业。

<?php
session_start();
$name = $age = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = strip_tags($_POST["name"]);
    $age = $_POST["age"] * 1;
    $_SESSION["name"] = $name;
    $_SESSION["age"] = $age;
} elseif (isset($_SESSION['name']) || isset($_SESSION['age'])) {
    if (isset($_SESSION['name'])) {
        $name = $_SESSION['name'];
    }
    if (isset($_SESSION['age'])) {
        $age = $_SESSION['age'];
    }
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
    <head>
        <title>Session demonstration</title>
    </head>

    <body>
        <h1>Session demonstration</h1>
        <a href="session-2.php">Demo session</a><br>
        <a href="session_destroy.php">Close session</a><br><br>
        <form action="<?= $_SERVER["PHP_SELF"] ?>" method="post">
            Your name is:
            <input type="text" name="name" value="<?php echo $name ?>"><br>
            You are:
            <input type="text" name="age" value="<?php echo $age ?>"><br>
            <input type="submit" value="Submit">
        </form>
<?php

    if ($name and $age) {
        echo "<h1>Hello, $name</h1>";
        echo "<h3>You are $age</h3>";
    } else {
        print "<h3>Bye!</h3>";
    }
?>
    </body>
</html>