无法将会话数据存储到下一个表单中

时间:2014-10-27 16:55:47

标签: php html validation session post

目前我正在讨论存储会话并将其传递给下一个表单的问题,但是当我尝试启动会话并将变量存储在会话中时,它很难实现。请详细说明一下,谢谢!

MainForm.php

<?php
session_start();
require("inputValidation.php"); // This php file is just a file that does validation for my side
$validForm = true;
if ($_POST) 
{
}
?>
<form class="form" action="nextform.php" role="form" method="post">
<input type="text" class="form-control" id="name" name="name" value= "<?php
                        if (isset($_POST['name'])) 
                            {
                            if (!validateRequired($_POST['name'])) 
                            {
                                $_SESSION['test'] = $_POST['name'];
                                $validForm = false;          
                            }
                            if (validateRequired($_POST['name'])) 
                            {
                                $_SESSION['test'] = $_POST['name'];
                                $validForm = true;
                            }
                        }
                        ?>
<input name="submit" type="submit" value="Submit" class="btn btn-primary">

nextform.php

print_r ($_SESSION);

问题是即使我在文本框名称中输入任何值,我将直接重定向到nextform.php而不获取我的会话值。为什么会这样?有没有办法在不改变action="nextform.php"的情况下获得会话价值?

谢谢!

对不起,我还是会话和PHP的新手,所以请耐心等待:)

1 个答案:

答案 0 :(得分:1)

基本上你要做的就是移动整个

if (isset($_POST['name']))
{
    //... you code
}

到提交表单的页面,在您的情况下nextform.php

您的网页应该是:

<强> MainForm.php

<form class="form" action="nextform.php" role="form" method="post">
<input type="text" class="form-control" id="name" name="name" value= "">
<input name="submit" type="submit" value="Submit" class="btn btn-primary">

<强> nextform.php

<?php
session_start();
require("inputValidation.php"); // This php file is just a file that does validation for my side
$validForm = true;

if (isset($_POST['name'])) 
{
    if (!validateRequired($_POST['name'])) 
    {
        $_SESSION['test'] = $_POST['name'];
        $validForm = false;          
    }
    if (validateRequired($_POST['name'])) 
    {
        $_SESSION['test'] = $_POST['name'];
        $validForm = true;
    }
}

if($validForm) {
    echo "Validation success";
    print_r ($_SESSION);
} else {
    echo "Form validation failed.";
}
?>

您基本上可以访问提交表单的页面中的POST参数,请参阅action="nextform.php"

您可以在此检查表单是否已提交并进行正确验证,并将用户重定向到某个位置,或者只是根据需要显示相应的消息,即Validation failedValidation success