Reputation: 25
I want to compare two passwords to make sure they match and redirect if not using php. I have written this code, but the code within the if statement does not execute even if the passwords dont match.
<?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');
?>
Upvotes: 2
Views: 1029
Reputation: 33542
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.
Upvotes: 0
Reputation: 26783
After the header
redirect command you need to exit;
otherwise the code just continues to run, giving duplicate header commands - the last one you send is the one that acts.
Upvotes: 1
Reputation: 28753
You change the Location
header again at the end of your script:
if(strlen($username)>30)
header('Location: register_form.php?error=1&usrlen=1');
/* ... */
header('Location: index.php');
My guess is the if
block is executing properly, but calling the header()
function a second time is changing the header. Try using an if-else
instead:
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');
}
Upvotes: 0