I'm trying to validate a registration form using HTML and PHP, and insert the data into an SQL database. Upon registration, I'd like for my user to be directed to their personal dashboard. I can get everything to work except for the redirect upon form submission.
Here is the PHP at the start of the page:
<?php
// define variables and set to empty values
$emailErr = $passErr = $confirmErr = $email = $pass = $confirm = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["pass"])) {
$passErr = "You must have a password";
} else {
$pass = test_input($_POST["pass"]);
}
if (empty($_POST["confirm"])) {
$confirmErr = "You must confirm your password";
} else {
$confirm = test_input($_POST["confirm"]);
}
if ($pass != $confirm) {
$confirmErr = "Your passwords must match";
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = test_input($_POST["email"]);
$pass = test_input($_POST["pass"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
And my HTML form:
<div class="container">
<form class="form-signin" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<h2 class="form-signin-heading">Register below:</h2>
<span class="error"><?php echo $emailErr;?></span>
<input type='email' class="form-control" placeholder="enter email..." name='email'/>
<span class="error"><?php echo $passErr;?></span>
<input type='password' class="form-control" placeholder="enter password" name='pass'/><span class="error"><?php echo $confirmErr;?></span>
<input type='password' class="form-control" placeholder="confirm password" name='confirm'/>
<input type='submit' class="btn btn-success btn-block" name="submit" value="submit">
<h5>Already have an account? <a href="login.html">Log in</a>.</h5>
</form>
</div>
Note the use of
<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
on
<form action="">
param. Using this function I can't get a redirect.
I've included my SQL entries following the HTML, and the entries are working just fine, but the header(); tag doesn't seem to work. See here:
<?php
$email = $_POST['email'];
$pass = md5($_POST['pass']);
// Database connection
require 'database.php';
$sql = "SELECT email FROM users WHERE email = '".$email."'";
$result = $conn->query($sql);
$row_count = $result->num_rows;
if ($row_count == 1) {
// user already exists
header('Location: login.php');
} elseif ($row_count > 1) {
// just to double check multiple entries aren't input into the DB
echo 'There are too many records with that name!';
} else {
// enter user into DB
$sql = "INSERT INTO users (email, pass)
VALUES ('".$email."', '".$pass."')";
if ($conn->query($sql) === TRUE) {
header('Location: dashboard.php');
exit();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
}
?>
Any ideas what I'm doing wrong?