有条件地重定向到另一个页面并通过PHP发送参数

时间:2017-02-07 00:57:49

标签: php html post

我有一个页面,它会从尝试在我的网站上创建新帐户的用户那里获取输入数据。虽然我想在重定向页面之前检查数据的值,以将输入数据发送到数据库。我创建了一个验证表单,当用户点击提交时重定向回同一页面,以便检查值,但是如果所有值都没问题,那么我想将输入的参数发送到另一个页面,然后输入它们数据库。有没有办法在PHP中有条件地执行此操作?我试图用一个简单的布尔检查实现它,如果输入的任何参数是不正确的,但不知道如何发送params以及重定向。

这是一个缩短版的代码,只有一些表格:

<?php
// Connection to database
include_once("createConnection.php");

$hasErrors = false;
$errorFName = $errorLName = $errorEmail = "";
$fName = $lName = $email = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["fName"])) {
    $errorFName = "This field is required.";
    $hasErrors = true;
} 
else {
    $name = validation($_POST["fName"]);
    //name cannot contain any symbols or numbers
    if (!preg_match("/^[a-zA-Z ]*$/",$fName)) {
      $errorFName = "Only letters and white space allowed"; 
      $hasErrors = true;
    }
}

if($hasErrors==false){
    **???**
}


function validation($input) { 
    $input = trim($input);
    $input = stripslashes($input);
    $input = htmlspecialchars($input);
    return $input;
}
?>

<form class="loginForm" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    <table class="loginTable">
        <tr>
            <td><label for="newDetail">First Name: </label>
                <input type="text" class="formBox" value="" id="newDetail" name="fName">
                <?php echo $errorFName;?>
            </td>
        </tr>
        <tr>
            <td><label for="newDetail">Password: </label>
                <input type="text" class="formBox" value="" id="newDetail" name="pword">
            </td>
        </tr>
        <tr>
            <td><button type="submit" class="loginButton" name="submitNew">Submit</button></td>
        </tr>

    </table>
</form>

谢谢!

3 个答案:

答案 0 :(得分:0)

您可以在会话中存储$ _POST变量。

$_SESSION["firstname"] = $_POST["fname"];

然后重定向到所需的页面

header("location: welcomepage.php");

然后从会话和进程中获取变量,可以插入数据库以备将来使用。

$firstname = $_SESSION["firstname"];

答案 1 :(得分:0)

您可以使用<meta http-equiv="refresh">手动重定向:

echo '<meta http-equiv="refresh" content="0, welcomepage.php?params=params">';

答案 2 :(得分:0)

我不太确定你为什么要将参数传递给其他页面 - 在这里处理它们要容易得多。如果它是您不喜欢的代码的一般信息 - 您可以将数据传递给包含文件中的函数或方法。

但是,如果确实需要从单独的页面保存数据,我建议您通过var captcha = Request.Unvalidated.Form["g-recaptcha-response"]; 发送数据:

cURL

这样,您在接收页面上输出的任何内容都将以$post = array(/*put all your variables here*/); $params = http_build_query($post); $url = 'http://your.domain.com/receiver.php'; $curl = curl_init($url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $params); $result = curl_exec($curl); 结尾,因此您可以向用户确认他/她的数据已保存。

NB:无论你最终会做什么 - 不要将数据作为GET传递给接收页面。这是不安全的,每当有人这样做,一只小狗就会死![/ p>

有关curl的更多信息:http://php.net/manual/en/book.curl.php