2

如果不使用 php,我想比较两个密码以确保它们匹配并重定向。我已经编写了这段代码,但是即使密码不匹配,if 语句中的代码也不会执行。

<?php 
include 'includes/dbcnx.php';
$username = $_POST['username'];
$password = $_POST['password'];
$pass2 = $_POST['pass2'];
$email = $_POST['email'];

if($password != $pass2)
    header('Location: register_form.php');
if(strlen($username)>30)
    header('Location: register_form.php?error=1&usrlen=1');

$username = mysql_real_escape_string($username);
$email = mysql_real_escape_string($email);
$salt = createSalt();
$hash = hash('sha256',$salt.$hash);
mysql_select_db("sealion");
$query = "INSERT INTO users (username, password, salt, email)
        VALUES ('$username','$hash','$salt','$email');";
mysql_query($query);
header('Location: index.php');
?>
4

3 回答 3

1

header重定向命令之后,您需要exit;否则代码将继续运行,给出重复的标头命令 - 您发送的最后一个是起作用的。

于 2012-09-19T23:27:28.537 回答
0

The code does execute, but a header() will not stop the rest of the code being executed on it's own:

if($password != $pass2)
{
    header('Location: register_form.php');
    exit;
}

On that note, your code might be easier to read if you put the entire suite of operations inside the conditional statement.

if($password != $pass2)
{
    header('Location: register_form.php');
}
else if(strlen($username)>30)
{
    header('Location: register_form.php?error=1&usrlen=1');
}
else
{
    // Do your updates here...
}

This would make your code easier to read by the next chap (or if you come back to in in six months time) - and would also make it impossible for multiple actions to happen.

于 2012-09-19T23:28:13.387 回答
0

Location您在脚本末尾再次更改标题:

if(strlen($username)>30)
    header('Location: register_form.php?error=1&usrlen=1');
/* ... */
header('Location: index.php');

我的猜测是该if块正在正确执行,但header()第二次调用该函数正在更改标题。尝试if-else改用:

if(strlen($username)>30) {
    header('Location: register_form.php?error=1&usrlen=1');
}
else {
    $username = mysql_real_escape_string($username);
    $email = mysql_real_escape_string($email);
    $salt = createSalt();
    $hash = hash('sha256',$salt.$hash);
    mysql_select_db("sealion");
    $query = "INSERT INTO users (username, password, salt, email)
            VALUES ('$username','$hash','$salt','$email');";
    mysql_query($query);
    header('Location: index.php');
}
于 2012-09-19T23:27:21.780 回答