Building a simple login page. If the user types in a password and password confirmation that don’t match, I want to reset the registration form and print an message. Currently, the message does not print, but carries on through the script. This is what I’ve tried, by way of setting a SESSION variable when the error occurs, and showing this variable upon reload:
registration.php:
<?php
session_start();
if (isset($_SESSION['errmsg'])) {
print($_SESSION['errmsg']);
unset($_SESSION['errmsg']);
}
?>
<form name="register" action="register.php" method="post">
<label>Username</label><input type="text" name="username" maxlength="20" />
<label>Password</label><input type="password" name="pass" />
<label>Password Again</label><input type="password" name="pass_confirm" />
<input type="submit" value="Register" />
</form>
register.php:
<?php
function create_salt() {
$string = md5(uniqid(rand(), true));
return substr($string, 0, 3);
}
session_start();
$username = $_POST['username'];
$pass = $_POST['pass'];
$pass_confirm = $_POST['pass_confirm'];
if ($pass != $pass_confirm) {
$_SESSION['errmsg'] = "Passwords do not match.";
header('Location: registration.php');
}
if (strlen($username) > 20) {
header('Location: registration.php');
}
$hash = hash('sha256', $pass);
$salt = create_salt();
$hash = hash('sha256', $salt . $hash);
$conn = mysql_connect('localhost', 'test4', 'test4');
mysql_select_db('test4', $conn);
$username = mysql_real_escape_string($username);
$query = "INSERT INTO users (username, password, salt) VALUES ('$username', '$hash', '$salt');";
mysql_query($query);
mysql_close();
header('Location: index.php');
?>
The important part is the line if ($pass != $pass_confirm) { .... Currently if the passwords do not match this condition is met, but it will carry on through the script rather than reloading via header(Location: registration.php). I am aware that header() cannot be invoked after data has been sent, which is probably causing the problem.
If so, is there a better way to do this in PHP or should I be looking at alternatives?
A
die();orexit;solves the problem.