Php redirect to page if statement

时间:2015-09-14 16:08:53

标签: php jquery redirect

I'm trying to make you redirect to the successful page after succesfully registering but whenever I click the register button I get redirected instantly even if all the input's are empty

if(isset($_POST["registration"])){
    if(!empty($_POST["gender"])
    and !empty($_POST["username"])
    and !strlen($_POST["username"]) < 3
    and !empty($_POST["email"])
    and !email($_POST["email"])
    and !empty($_POST["emailver"])
    and !verification($_POST["email"],$_POST["emailver"])
    and !empty($_POST["password"])
    and !strlen($_POST["password"]) < 8
    and strlen($_POST["password"]) < 25
    and checkUppercase($_POST["password"])
    and checkLowercase($_POST["password"])
    and checkNumber($_POST["password"])
    and !empty($_POST["passwordver"])
    and !verification($_POST["password"],$_POST["passwordver"])){
        if(addgamer($db,$_SESSION["gender"],$_SESSION["username"],$_SESSION["email"],$_POST["password"]) === TRUE){
            $url = 'succesfull.html';
            header($url);
        }
    }
}

The function for addgamers

function addgamer($db,$gender,$username,$email,$password){

    $sql = "INSERT INTO gamers (`gender`, `username`, `email`, `password`) VALUES('$gender','$username','$email','$password')";
    $db -> exec($sql);
    if ($db->query($sql) === TRUE) {
        $GamerId = $db -> lastInsertId();
        $_SESSION['GamerId'] = $GamerId;
        return true;
    } else {
        return false;
    }
}

I found some answers here but all of them do the same and I have no solution for this.

GOTO($url);

Or

header('location: $url');

Or

if(addgamer($db,$_SESSION["gender"],$_SESSION["username"],$_SESSION["email"],$_SESSION["password"]) === FALSE ){
    die();
}else{
    $url = 'successful.php';
    header($url);
}

Also tried with jQuery

echo "<script>window.location = '$url'</script>";

On every single click on the registration submit button you get redirected to the successful page but that should not happen until everything is filled in correctly as shown from the above code.

As you can also see I'd like to fix this problem trying with php only first.

2 个答案:

答案 0 :(得分:2)

You have a missunderstanding PHP problem. If your form use a submit form, it will post automatically to the php page targeted. If you don't want to post to a new page and still verify your data, then you must use ajax in jquery : http://api.jquery.com/jquery.post/ . With that you ll catch your data without unexpected redirection. Once all your form is validated by your php code during ajax call, you can redirect in jquery on the callback function.

Hope this will help, I ve been through this step and I remember it was painful

答案 1 :(得分:2)

在提交表单之前进行验证首先会更好。 正如@Nicolas D所提到的,你也应该知道表单动作是你指向的页面,无论如何。

但是,您可以使用action=""action="<?php echo $_SERVER['PHP_SELF']; ?>"

将其设置为当前页面

这最后可能带有漏洞利用,您可以使用"htmlentities($_SERVER['PHP_SELF'])"代替。阅读here