I am trying to create a register page and I was wondering if there is a better way of doing this. So what I was think was instead of typing every field or is this a good way of doing this?
This is what I have currently.
This is the form
<form action="" method="POST">
<input type="text" name="username" placeholder="Username:" />
<input type="password" name="password" placeholder="Password:" />
<input type="password" name="password" placeholder="Confirm password:" />
<input type="text" name="email" placeholder="Email:" />
<input type="text" name="first_name" placeholder="First name:" />
<input type="text" name="last_name" placeholder="Last name:" />
<input type="submit" name="register" value="REGISTER" />
</form>
This is what I have for PHP side
function reg_validation() {
if ($_POST['register']) {
if (empty($_POST['username'])) {
echo 'Please enter a username';
}
if (empty($_POST['password'])) {
echo 'Please enter a password';
}
if (empty($_POST['confirm_password'])) {
echo 'Please confirm your password';
}
if (empty($_POST['email'])) {
echo 'Please enter an email address';
}
if (empty($_POST['first_name'])) {
echo 'Please enter your first name';
}
if (empty($_POST['last_name'])) {
echo 'Please enter your last name';
}
}
}
<?php
function reg_validation() {
if (isset($_POST['register'])) {
$expectedFields = array(
'username', 'password', 'confirm_password', 'email', 'first_name', 'last_name'
);
foreach ($expectedFields as $value)
if (!array_key_exists($value, $_POST) || empty($_POST[$value]))
return false;
return true;
}
return false;
}
?>
Don't know if I misunderstood your question in my last answer, so here is another suggestion. Code is not tested, so it may contain minor typos.
In this suggestion we store all field names in an array an loop through the array and checks if any of the field names is not a key in the post array.
So this function will return true if all fields is found in post data or false if not.
<?php
if (isset($_POST['register'])) {
try {
if (empty($_POST['username']))
throw new Exception('missing_username');
else if (empty($_POST['password']))
throw new Exception('missing_password');
else if (empty($_POST['confirm_password']))
throw new Exception('missing_confirm_pass');
else if (empty($_POST['email']))
throw new Exception('missing_email');
else if (empty($_POST['first_name']))
throw new Exception('missing_firstname');
else if (empty($_POST['last_name']))
throw new Exception('missing_lastname');
// do something if all fields are filled
} catch (Exception $e) {
$errorArray = array(
'missing_username' => 'Please enter a username',
'missing_password' => 'Please enter a password',
'missing_confirm_pass' => 'Please confirm your password',
'missing_email' => 'Please enter an email address',
'missing_firstname' => 'Please enter your first name',
'missing_lastname' => 'Please enter your last name'
);
if (isset($errorArray[$e->getMessage()]))
echo $errorArray[$e->getMessage()];
}
}
?>
I like to do it this way, don't know what everyone else thinks about it.
By using try catch, we don't neccessarily need a function to return, since we instead can throw an exception to break from the try section.
Related
This is my registration form I am using both javascript and php for validating form, javascript code works well in showing validation error messages however somethings wrong with php code,when javascript is disabled php code should show form validation error messages by refrshing page on form submit,but no error messages appear and no data is inserted. On clicking submit, page is reloaded but even form does not appear.
<?php
error_reporting('E_ALL ^ E_NOTICE');
if(isset($_POST['reg'])){
$fn = ucfirst($_POST['fname']);
$ln = ucfirst($_POST['lname']);
$un = $_POST['username'];
$em = $_POST['email'];
$pswd = $_POST['password'];
$d= date("Y-m-d");
if (strlen($fn) < 2 || strlen($fn) > 15) {
$error = "First name must be 2 to 15 characters long";
}
elseif (strlen($ln) < 2 || strlen($ln) > 15) {
$error = "Last name must be 2 to 15 characters long";
}
elseif($em==""){
$error = "Email cannot be empty";
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$er = "Invalid email format";
}
elseif($pswd==""){
$error = "Fill your password";
}
elseif($pswd!=$pswd2){
$error = "Password and Confirm password do no match";
}
else{
$pswd = password_hash($pswd, PASSWORD_DEFAULT);
$stmt = $db->prepare("INSERT INTO table1 (username,firstname,lastname,email,password) VALUES (:username,:firstname,:lastname,:email,:password)");
$stmt->execute(array(':username'=>$un,':firstname'=>$fn,':lastname'=>$ln,':email'=>$em,':password'=>$pswd));
}
if ($stmt->rowCount() == 1) {
header("Location:login.php");
}
else {
echo "Error occured please try again.";
}
}
?>
<form action="" method="post">
<input type="text" name="fname" id="fn" placeholder="First Name"/><br />
<input type="text" name="lname" id="ln" placeholder="Last Name"/><br />
<input type="text" name="username" id="un" placeholder="Username" class="username" /><br />
<input type="email" name="email" id="em" placeholder="Email"/> <br />
<input type="password" name="password" id="pswd" placeholder="Password"/><br />
<input type="password" name="password2" id="pswd2" placeholder="Confirm Password"/><br />
<input type="submit" id="submit" name="reg" value="Create an Account">
<center><div id="er"><?php echo $error ?></div></center>
</form>
You should echo $error not $er
<center><div id="er"><?php echo $error; ?></div></center>
You are doing a mistake:
$stmt->execute(array(':username'=>$un,':firstname'=>$fn,':lastname'=>$ln,':email'=>$em,':password'=>$pswd));
You should use 'username' instead of ':username'. like this:
$stmt->execute(array('username'=>$un,'firstname'=>$fn,'lastname'=>$ln,'email'=>$em,'password'=>$pswd));
There are a few inconsistencies in your code.
At the beginnig you assign $_POST['email'] to $em, but later you validate against a variable named $email, which doesn't exist at this point.
$em = $_POST['email'];
.
.
.
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$er = "Invalid email format"; //should maybe be $error
}
Then there is the password-validation:
elseif($pswd!=$pswd2){
$error = "Password and Confirm password do no match";
}
$pswd2 has never been defined in your code.
$stmt ist defined in the else-block of your validation, but you use it for getting the row-count after the validation. So, if any of your if-statements is true, this will cause an error.
It would be better if you change that part of your code to this:
else{
$pswd = password_hash($pswd, PASSWORD_DEFAULT);
$stmt = $db->prepare("INSERT INTO table1 (username,firstname,lastname,email,password) VALUES (:username,:firstname,:lastname,:email,:password)");
$stmt->execute(array(':username'=>$un,':firstname'=>$fn,':lastname'=>$ln,':email'=>$em,':password'=>$pswd));
if ($stmt->rowCount() == 1) {
header("Location:login.php");
}
else {
echo "Error occured please try again.";
}
}
After all it seems like you haven't error reporting activatet.
imagine i have an errors array to contain any errors from a registration form, and i have a function called output_errors(), whose argument is the errors array.
is there a way to customise a pop up window to display the function to display the errors?
<?php
$error = array();
function output_errors($errors) {
return '<ul><li>' . implode('</li><li>',$errors) . '</li></ul>';
}
if (user_exists($_POST['username']) === true) {
$errors[] = 'Sorry, the username \'' . $_POST['username'] . '\' is already taken.';
}
if (preg_match("/\\s/", $_POST['username']) == true) {
$errors[] = 'Your username must not contain any spaces.';
}
if (strlen($_POST['password']) < 6) {
$errors[] = 'Your password must be at least 6 characters';
}
if ($_POST['password'] !== $_POST['password_again']) {
$errors[] = 'Your passwords do not match';
}
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'A valid email address is required';
}
if (email_exists($_POST['email']) === true) {
$errors[] = 'Sorry, email \'' . $_POST['email'] . '\' exists.';
}
if (empty($_POST) === false && empty($errors) === true) {
$register_data = array(
'username' => $_POST['username'],
'password' => $_POST['password'],
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email']
);
register_user($register_data);
header('Location: register.php?success');
exit();
} else if(empty($errors) === false) {
echo output_errors($errors);
?>
<form action="" method="post">
<ul>
<li>
<i>*All fields marked with asterisk are required!</i><br>
<input type="text" placeholder="Username" name="username">
</li>
<li>
<br>
<input type="password" placeholder="*Password" name="password">
</li>
<li>
br>
<input type="password" placeholder="*Retype Password" name="password_a">
</li>
<li>
<br>
<input type="text" placeholder="*First name" name="first_name">
</li>
<li>
<br>
<input type="text" placeholder="Last name" name="last_name">
</li>
<li>
<br>
<input type="text" placeholder="*Email" name="email">
</li>
<li>
<input type="submit" value="Register">
</li>
</ul>
</form>
You can't customize the by-default pop-up of JavaScript, either you can use Bootstrap or do something like:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Test!</button>
<script>
function myFunction() {
var myWindow = window.open("", "MsgWindow", "width=200, height=100");
myWindow.document.write("<p>This is 'MsgWindow'. I am 200px wide and 100px tall!</p>");
}
</script>
</body>
</html>
In the document.write(content), here content will be your error message.
You can insert your php in js by doing:
document.write(<?php echo "Text"; ?>);
See if that helps.
I'm not sure if this is what you're looking for but if you replace the echo statement in the last line with this:
echo "<script>";
echo "window.open('', 'MsgWindow', 'width=200, height=100').document.write('" . output_errors($errors) . "');";
echo "</script>";
You will get a pop-up window with the errors displayed in it. That being said there are a few errors in your code which make the errors display immediately, specifically your password fields. So the above will work but you'll have a pop-up window as soon as the page is loaded.
Continuing from my previous post "PHP and MYSQL database connection and table creation only once", I created the registration form with the PHP code and server side validation. I’m getting some errors as stated below.
i.e. all errors are occurring at the place where i try to print the errors in their respected html class “”. I've made the html "span class" text bold for easy recognition. If their is anything extra solutions for better performance of the form please let me know...
List of errors:
Notice: Undefined variable: error_name in C:\wamp\www\18+\register.php
Notice: Undefined variable: error_username in C:\wamp\www\18+\register.php
Notice: Undefined variable: error_password in C:\wamp\www\18+\register.php
Notice: Undefined variable: error_password2 in C:\wamp\www\18+\register.php
Notice: Undefined variable: error_email in C:\wamp\www\18+\register.php
Register.php
<?php
include ‘database.php';
session_start();
if (isset($_POST['submit'])) {
$error = " "; //Declare a null variable to store error messages
//validation for fullname
if (empty($_POST['fullname'])) {
$error_name = 'Enter Fullname...';
} else {
$fullname = mysql_real_escape_string(trim($_POST['fullname']));
}
//validation for username
if (empty($_POST['username'])){
$error_username = 'Enter Username...';
} else {
$username = mysql_real_escape_string(trim($_POST['username']));
}
//validation for password
if(empty($_POST['password'])){
$error_password = 'Please Enter Your Password...';
} else {
if (empty($_POST['password2'])) {
$error_password2 = 'Re-enter Your Password...';
} else {
if(($_POST['password'])!=($_POST['password2'])){
$error_password2 = 'Passwords Do not match...';
} else {
$confirm = mysql_real_escape_string(md5($_POST['password2']));
}
}
}
//validation for e-mail
if (empty($_POST['email'])) {
$error_email = 'Please Enter your Email ';
} else {
if (preg_match("//custom preg match characters", $_POST['e-mail'])) {
//regular expression for email validation
$email = mysql_real_escape_string($_POST['email']);
} else {
$error_email = 'Your E-mail Address is invalid ';
}
}
if (empty($error)) //send to Database if there's no error '
{
$query= "DB INSERT QUERY";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo 'Failed to Register Your Account...!';
} else {
echo 'Account Registered Successfully...!';
}
}
mysqli_close($sql);//Close the DB Connection
}
?>
Index.php
<form action="register.php" method="post" id="user_registration">
<p id="head">Create Account</p>
<input type="text" id="fullname" name="fullname"/>
**<span class="error" id="fullname"><?php echo $error_name; ?></span>**
<input type="text" id="username" name="username"/>
<span id="availability_status"></span>
**<span class="error" id="username"><?php echo $error_username; ?></span>**
<input type="password" id="password" name="password"/>
**<span class="error" id="password"><?php echo $error_password; ?></span>**
<input type="password" id="password2" name="password2"/>
**<span class="error" id="divCheckPasswordMatch"><?php echo $error_password2;?></span>**
<input type="email" id="email" name="email"/>
**<span class="error" id="email"><?php echo $error_email; ?></span>**
<p class="submit">
<button type="submit"id="submit" name="submit" value="Register”>Register</button>
</p>
</form>
First of all You need to fix the quote at include ‘database.php'; to include 'database.php'; never use curly quote due to this all your code is being blocked.
Next You need to initialize all variable to null or simply ""
OR
You can check if the variable exist or not using isset() like if you want to print value of an variable $val then use this if(isset($val)) echo $val;
UPDATE
You can easily use an array to store errors:
simply use like
$error['name']='Enter Fullname...';
And to check if name error occurs use
if(isset($error['name'])){
//Its an error print error
}
you may need to define these variable on top of the page before using them in code something like this.
$error_name = '';
$error_username = '';
$error_password = '';
$error_password2 = '';
$error_email = '';
Put an else to your if (isset($_POST['submit']))
else { /* What if the user didn't click submit? Else is the answer */
$error_name="";
$error_username="";
$error_password="";
$error_password2="";
$error_email="";
}
The problem is, you are setting the messages only if certain conditions are true. Thus, these variables are not found if those conditions aren't true. To resolve this, use isset() when displaying the errors, e.g.
<?php echo isset($error_name)?$error_name:'' ; ?>
This means check if $error_name is set, if yes display it or display nothing.
Another thing (logically) is that your code is not actually checking for the errors. The $error remains an empty string and you are checking if it is empty which will always be true. You need to either store the errors as arrays or check if all the variables are empty.
Additional:
Can u tell me how to store the errors as arrays..plz
Try this:
<?php
include 'database.php';
session_start();
if (isset($_POST['submit'])) {
$error = array(); //<-- Declare array here
//validation for fullname
if (empty($_POST['fullname'])) {
$error['fullname'] = 'Enter Fullname...'; //<-- adding error into array
} else {
$fullname = mysql_real_escape_string(trim($_POST['fullname']));
}
//validation for username
if (empty($_POST['username'])){
$error['username'] = 'Enter Username...'; //<-- here too and so on..
} else {
$username = mysql_real_escape_string(trim($_POST['username']));
}
//validation for password
if(empty($_POST['password'])){
$error['password'] = 'Please Enter Your Password...';
} else {
if (empty($_POST['password2'])) {
$error['password2'] = 'Re-enter Your Password...';
} else {
if(($_POST['password'])!=($_POST['password2'])){
$error['password2'] = 'Passwords Do not match...';
} else {
$confirm = mysql_real_escape_string(md5($_POST['password2']));
}
}
}
//validation for e-mail
if (empty($_POST['email'])) {
$error['email'] = 'Please Enter your Email ';
} else {
if (preg_match("//custom preg match characters", $_POST['e-mail'])) {
//regular expression for email validation
$email = mysql_real_escape_string($_POST['email']);
} else {
$error['email'] = 'Your E-mail Address is invalid ';
}
}
if (!empty($error)) //send to Database if there's no error '
{
$query= "DB INSERT QUERY";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo 'Failed to Register Your Account...!';
} else {
echo 'Account Registered Successfully...!';
}
}
}
?>
Change your HTML to:
<form action="register.php" method="post" id="user_registration">
<p id="head">Create Account</p>
<input type="text" id="fullname" name="fullname"/>
<!-- checking if error message is set -->
**<span class="error" id="fullname"><?php echo isset($error['fullname'])?$error['fullname']:''; ?></span>**
<input type="text" id="username" name="username"/>
<span id="availability_status"></span>
**<span class="error" id="username"><?php echo isset($error['username'])?$error['username']:''; ?></span>**
<input type="password" id="password" name="password"/>
**<span class="error" id="password"><?php echo isset($error['password'])?$error['password']:''; ?></span>**
<input type="password" id="password2" name="password2"/>
**<span class="error" id="divCheckPasswordMatch"><?php echo isset($error['password2'])?$error['password2']:''; ?></span>**
<input type="email" id="email" name="email"/>
**<span class="error" id="email"><?php echo isset($error['email'])?$error['email']:''; ?></span>**
<p class="submit">
<button type="submit"id="submit" name="submit" value="Register">Register</button>
</p>
</form>
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
I am completely stumped with this (that, or I've just been staring at it for too long that there is an obvious error and I can't see it)
I've got a simple form which validates on the same page which is a custom template I have made
<form action="" method="post">
<input type="text" id="name" name="name" placeholder="Please enter your full name" />
<input type="email" id="email" name="email" placeholder="Please enter your email address" />
<input type="hidden" name="newsletterform" value="newsletterform" />
<input class="submit" type="submit" name="submit" id="searchsubmit" value="submit" />
</form>
It is then validated like so
<?php
$formsubmitted = (!empty($_POST['newsletterform'])) ? $_POST['newsletterform'] : "";
if($formsubmitted !== ''){
$fullname = (!empty($_POST['name'])) ? $_POST['name'] : "";
$email = (!empty($_POST['email'])) ? $_POST['email'] : "";
$failed = '';
if (empty($fullname)){
$failed.= 'Please enter your name.<br />';
}
if (empty($email)){
$failed.= 'Please enter your email address.<br />';
}
}
if ($failed == '' and $formsubmitted !== ''){ ?>
<div id="success-title">
Thank you for signing up!
</div>
<?php
}
if ($failed !== '' and $formsubmitted !== '') { ?>
<div id="error-title">
Sorry, we could not accept the details you submitted to us. Please see below.
</div>
<div id="error-body">
<?php echo $failed;?>
</div>
<?php } ?>
It shows the errors when you try to send an empty form, it validates the email fine when there is a value in there and when the name field is empty. When something is entered into the name field when there is something or nothing in the email field it goes to my 404 page.
The solution is very simple, avoid using in forms the name attribute called "name".
change:
<input type="text" id="name" name="name" placeholder="Please enter your full name" />
to:
<input type="text" id="name" name="myname" placeholder="Please enter your full name" />
Additional info:
Unsafe Names for HTML Form Controls
For me it works fine in this way, try replace your PHP with this:
<?php
$failed = '';
$formsubmitted = (!empty($_POST['newsletterform'])) ? $_POST['newsletterform'] : "";
if($formsubmitted !== ''){
$fullname = (!empty($_POST['name'])) ? $_POST['name'] : "";
$email = (!empty($_POST['email'])) ? $_POST['email'] : "";
if (empty($fullname)){
$failed.= 'Please enter your name.<br />';
}
if (empty($email)){
$failed.= 'Please enter your email address.<br />';
}
}
if ($failed == '' and $formsubmitted !== ''){
echo '<div id="success-title">
Thank you for signing up!
</div>';
}
if ($failed !== '' and $formsubmitted !== '') {
echo '<div id="error-title">
Sorry, we could not accept the details you submitted to us. Please see below.
</div>
<div id="error-body">';
echo $failed;
echo '</div>';
}
?>
You can do this --
<?php
if (strlen($fullname) < 3) {
// name too short, add error
$errors['name_error'] = 'Your name is required';
}elseif(strlen($fullname) ==0){
$errors['name_error'] = 'Your name is required';
}
if (strlen($email) == 0) {
// no email address given
$errors['email_error'] = 'Email address is required';
} else if ( !preg_match('/^(?:[\w\d]+\.?)+#(?:(?:[\w\d]\-?)+\.)+\w{2,4}$/i', $email)) {
// invalid email format
$errors['email_error'] = 'Email address entered is invalid';
}
if (sizeof($errors) == 0) {
echo '<div id="success-title">
Thank you for signing up!
</div>';
}
else {
echo 'Sorry, we could not accept the details you submitted to us. Please see below.' . $errors;
}
?>
UPDATE:
Code is written as is and will stay that way. However, now it doesn't submit the data the user wrote in the form to the database. What's wrong.
Here is the first file. It contains the XML HTTP REQUEST and html form. This file also contains the wild .
<!DOCTYPE html>
<html>
<head>
<?php
require_once 'core/init.php';
?>
<meta charset="utf-8" />
<title></title>
<script src="http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js">
//directly below is that wild script tag
</script>
<script type="text/javascript">
function load(thefile, thediv) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject ('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
parameters1 = 'username='+document.getElementById('username').value;
parameters2 = 'email='+document.getElementById('email').value;
parameters3 = 'password='+document.getElementById('password').value;
parameters4 = 'password_again='+document.getElementById('password_again').value;
parameters5 = 'first_name='+document.getElementById('first_name').value;
parameters6 = 'last_name='+document.getElementById('last_name').value;
xmlhttp.open('POST', thefile, true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(parameters1 + '&' + parameters2 + '&' + parameters3 + '&' +
parameters4 + '&' + parameters5 + '&' +parameters6);
}
</script>
</script>
<title>Pop Up Sign Up</title>
</head>
<body>
<div id="popupbox">
<form name="signup" action="" method="post">
Desired Username:
<input id="username" placeholder="Username" value="<?php echo
(isset($desired_username) ? strip_tags($desired_username) : '');?>" type="text"
placeholder="Bob123" name="username" size="14" />
<br /> <br />
Your Email:
Register
<input id="email" placeholder="jasontanner328#gmail.com" value="<?php echo
(isset($desired_email) ? strip_tags($desired_email) : '');?>" type="email"
name="email" size="14" />
<br /> <br />
Your Password:
<input id="password" placeholder="Password" name="password" type="password"
size="14" />
<br /> <br />
Your Password Again:
<input id="password_again" placeholder="Password Again"
name="password_again" type="password" size="14" />
<br /> <br />
First Name:
<input id="first_name" placeholder="Jason" value="<?php echo
(isset($desired_first_name) ? strip_tags($desired_first_name) : '');?>"
name="first_name" type="text" size="14" />
<br /> <br />
Last Name:
<input id="last_name" placeholder="Tanner" name="last_name" value="<?php echo
(isset($desired_last_name) ? strip_tags($desired_last_name) : '');?>" type="text"
size="14" />
<br /> <br />
<center><input type="button" name="submit" value="Register"
onclick="load('register.php', 'popupbox');" /></center>
</form>
</div>
<span id="result">
</span>
</body>
</html>
Here is the second file that deals with inserting the data into the server and what I want to return after the submit button has been clicked on.
<?php
require_once 'core/init.php';
logged_in_redirect();
if (empty($_POST) === false) {
$desired_username = $_POST['username'];
$desired_email = $_POST['email'];
$desired_first_name = $_POST['first_name'];
$desired_last_name = $_POST['last_name'];
$required_fields = array
('username','email','password','password_again','first_name','last_name');
foreach ($_POST as $key=>$value) {
if (empty($value) && in_array($key, $required_fields) === true) {
$errors[] = 'Fields marked with an asterisk are required.';
break 1;
}
}
if (empty($errors) === true) {
if (user_exists($_POST['username']) === true || strlen($_POST ['username']) < 6) {
$errors[] = 'Sorry, the username \'' . $_POST['username'] . '\' is already taken
or is too short. 6 characters are the minimum.';
}
if (preg_match("/\\s/", $_POST ['username']) == true) {
$errors[] = 'Sorry there is a space in your username.';
}
if (strlen($_POST ['password']) < 6) {
$errors[] = 'Your password must be at least 6 characters';
}
if ($_POST ['password'] !== $_POST['password_again']) {
$errors[] = 'Make sure both passwords submitted are the same.';
}
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'A valid email address is required.';
}
if (email_exists($_POST['email']) === true) {
$errors[] = 'Sorry, the email \'' . $_POST['email'] . '\' is already in use.';
}
if (strlen($_POST ['first_name']) < 2) {
$errors[] = 'Your first name must contain at least two characters.';
}
if (strlen($_POST ['last_name']) < 2) {
$errors[] = 'Your last name must contain at least two characters.';
} }
} else {
//if (isset($_GET['success']) && empty($_GET['success'])) {
//echo 'You have successfully registered. Please check your email to activate your
account.';
// } else {
if (empty ($_POST) === false && empty($errors) === true){
$register_data = array(
'username' => $_POST['username'],
'password' => $_POST['password'],
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email'],
'email_code' => md5($_POST['username'] + microtime())
);
register_user($register_data);
echo 'WIN';
// header('Location: register.php?success');
// exit();
// } else
if (empty($errors) === false){
echo output_errors($errors);
}
}}
?>
The button on your form is type="submit"; This will submit the form and redirect the page, unless you have it return false; in the onclick attribute. I would suggest, rather, to change the button to a regular button instead of a submit-button:
<input type="button" name="submit" value="Register" onclick="load('register.php', 'result');" />
This change will stop your page from redirecting after submitting the form.
EDIT: After reviewing the full code, the POST-page looks like it has a logic error in the processing (and a few syntax errors; see my comment on the question regarding closing curly braces).
The if (empty($errors) === true) { block ends with an } else { and inside the else-block you output that the user has successfully registered. Translated, this means "if there is an initial error, tell the user they successfully registered." Instead, change everything after (and including) the } else { to:
if (!empty($_POST) && empty($errors)) {
// the form has been submitted and there are no errors
echo 'You have successfully registered. Please check your email to activate your account.';
$register_data = array(
'username' => $_POST['username'],
'password' => $_POST['password'],
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email'],
'email_code' => md5($_POST['username'] + microtime())
);
register_user($register_data);
} else if (!empty($errors)) {
// there are errors =[
echo output_errors($errors);
}