I have a form submitting to intself. If the post variables are set, then I want them to be redirected to employee_profile.php. Currently the header location does not work even when the post variables are set. Any ideas?
<?php
$email_error = $password_error = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$email_error = "Missing Email";
} else {
$email = $_POST["email"];
}
if (empty($_POST["password"])) {
$password_error = "Missing Password";
} else {
$email = $_POST["email"];
$password = $_POST["password"];
header ('Location: employee_profile.php');
}
}
?>
The form:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
Email: <input type="text" name="email" value="<?php echo htmlspecialchars($email);?>">
<span class="error"><?php echo $email_error;?></span><br />
Password: <input type="password" name="password">
<span class="error"><?php echo $password_error;?></span><br />
<input type="submit" value="Submit">
</form>
The PHP header (using HTTP/1.1) redirect requires an absolute URL.
Try the following:
<?php
// from PHP documentation, see http://php.net/manual/de/function.header.php
$host = $_SERVER['HTTP_HOST'];
// or:
// $host = $_SERVER['SERVER_NAME'];
$email_error = $password_error = "";
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["email"])) {
$email_error = "Missing Email";
} else {
$email = $_POST["email"];
}
if(empty($_POST["password"])) {
$password_error = "Missing Password";
} else {
$password = $_POST["password"];
}
// some additional fixes: finally check if both is valid
if($email_error == $password_error) {
header("Location: http://$host/employee_profile.php");
}
}
?>
you can try some thing like this. currently in your script even when the email is not set but password is set, header function is called.
$email = (isset($_POST['email']) && !empty($_POST['email'])) ? $_POST['email'] : "Missing Email";
$password = (isset($_POST['password']) && !empty($_POST['password'])) ? $_POST['password'] : "Missing Password";
if($email != "Missing Email" && $password != "Missing Password"){
header ('Location: employee_profile.php');
}
(warning: here any values passed as email and password will get the user to employee_profile)
also see if you are printing some thing or some htmls before calling header.
is it throwing any error, if so can you also print the error here?
Related
The POST form works fine and all the data is submitted properly, $captcha_code is returning the correct output and so is $captcha. However, when I check if $captcha == $captcha_code it always returns failure. Can someone please explain as to why this happens?
include 'inc/simple-php-captcha/simple-php-captcha.php';
$_SESSION['captcha'] = simple_php_captcha();
$captcha_code = $_SESSION['captcha']['code'];
if(isset($_POST['register'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
$captcha = $_POST['captcha'];
if($captcha == $captcha_code) {
echo 'captcha success';
} else {
echo 'captcha failure';
}
}
You need to generate the captcha before itself in login.php
login-form.php
<?php
// start session and generate captcha and it's image
session_start();
include 'inc/simple-php-captcha/simple-php-captcha.php';
$_SESSION['captcha'] = simple_php_captcha();
// render the form
?>
<input type="text" name="email">
<input type="text" name="password">
..
..
<input type="text" name="captcha">
<img src="<?php $_SESSION['captcha']['image_src']; ?>">
<input type="submit">
login-submit.php
$captcha_code = $_SESSION['captcha']['code']; //retrive what code was generated before
if(isset($_POST['register'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
$captcha = $_POST['captcha'];
if($captcha == $captcha_code) { // try matching
echo 'captcha success';
} else {
echo 'capture failure';
}
}
registration_from.php
<!DOCTYPE HTML>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="" method="POST">
Name:
<input type="text" name="name">
<br/> <br/>
Username:
<input type="text" name="username">
<br/> <br/>
Password:
<input type="password" name="password">
<br/> <br/>
Email:
<input type="text" name="email">
<br/> <br/>
<input type="submit" name="submit" value="Register">
</form>
</body>
</html>
<?php
require('connect.php');
require('validation.php');
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if(isset($_POST["submit"])){
if($query = mysqli_query($connect,"INSERT INTO users
(`id`,`name`,`username`, `password`, `email`) VALUES ('','".$name."',
'".$username."', '".$password."', '".$email."')")){
echo "Success";
}else{
echo "Failure" . mysqli_error($connect);
}
}
?>
validation.php
<?php
// define variables and set to empty values
$nameErr = $emailErr = $userErr = $passwordErr = "";
$name = $email = $username =$password = "";
if (isset($_POST['submit'])) {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["username"])) {
$userErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password= test_input($_POST["password"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
connect.php
<?php
$connect = mysqli_connect("localhost", "root", "","php_forum")
or die("Error " . mysqli_error($connect));
?>
I'm developing a simple Registration from with four inputs i.e., Name, username, password, email.when the user fills out the form and click submit button then all the filled data should go n save in data base which is working fine in my case, but when the user wont fill any data and if user simply clicks a submit button then error message should be shown like "ALL FIELDS ARE NECESSARY", but where in my case even if i click submit button without entering any values the mesage i'm getting as success and all the null values are getting stored in the data base which should not happen, my output should be if i fill the forms n click submit button then all the data should be stored in database and if i click submit button without filling out any value then error should throw that "all field to be filled" and no null value should be stored in data base, please can any one guide me what changes i should do so that to get my desired output.
If you don't mind adding a little more code, you code do like:
In your registration_form.php
<?php
require('validation.php'); // Require first to do validation before queries
require('connect.php');
// Remove the part where you set variables to $_POST params
// Variables are already set inside validation.php
/**
* Then, I recommend moving queries to **connect.php**
* to have all your sql functions inside one file.
* Also moving the inserting of data to a function for easy grouping/calling
*/
if (isset($_POST["submit"]) {
// Check if validation does not fail
if ($emailErr == "" || $nameErr == "" || $userErr == "" || $passwordErr == "") {
// Call to insert function
doInsert($name, $email, $username, $password);
} else {
echo $emailErr . " " . $nameErr . " " . $userErr . " " . $passwordErr;
}
}
?>
In your connect.php
function doInsert($name, $email, $username, $password) {
$connect = mysqli_connect("localhost", "root", "","php_forum")
or die("Error " . mysqli_error($connect));
$sql = "INSERT INTO users(`id`,`name`,`username`, `password`, `email`)
VALUES ('','".$name."', '".$username."', '".$password."', '".$email."')";
$query = mysqli_query($connect, $sql);
if ($query) {
echo "Success";
} else {
echo "Failure " . mysqli_error($connect);
}
}
Please add error in session and print session in form file.
In validation.php
$nameErr = $emailErr = $userErr = $passwordErr = "";
$name = $email = $username =$password = "";
if (isset($_POST['submit'])) {
$name = $_POST["name"];
$email = $_POST["email"];
$username = $_POST["username"];
$password = $_POST["password"];
if($name == '' || $email == '' || $username == '' || $password == "")
{
echo "ALL FIELDS ARE NECESSARY";
exit();
}
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["username"])) {
$userErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password= test_input($_POST["password"]);
}
}
registration_from.php
if(isset($_SESSION['error]) && !empty($_SESSION['error])){
echo $_SESSION["error"]
}
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
Im a beginner and I am facing this issue. I know this is simple, but am not able to debug this:
<!DOCTYPE html>
<html>
<body>
<form action="process.php" method="POST">
Username: <input type="text" name="user"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
The PHP processing it is as follows. But I always get "NOT VALID" even though the credentials are right.
<?php
$name= $_POST['user'];
$password = $_POST['password'];
if($name=="admin"){
if($password=="admin123")
echo "VALID";
}
else
echo "NOT VALID";
?>
Use && Condition rather then two if condition. Try this one.
Use Logical Operators. Check more operators Demo Logical Operator
<?php
$name= $_POST['user'];
$password = $_POST['password'];
if($name=="admin" && $password=="admin123"){
echo "VALID";
header('Location: http://www.google.com/');exit;
}
else
{
echo "NOT VALID";
}
?>
You could use trim() function on your POST data.
$name = trim($_POST['user']);
$password = trim($_POST['password']);
if ($name == "admin" && $password == "admin123") {
echo "VALID";
} else {
echo "NOT VALID";
}
I have tried code like this
$name = "admin";
$password = "admin123";
if($name=="admin"){
if($password=="admin123")
echo "VALID";
}
else
echo "NOT VALID";
and it's show me VALID it'mean you enterd value is wrong,may be it consume space
Correct way to do is always check "variable isset" or not
<?php
$name= trim($_POST['user']);
$password = trim($_POST['password']);
if((isset($name) && $name == "admin") &&
(isset($password ) && $password=="admin123")){
echo "VALID";
}else{
echo "NOT VALID";
}
?>
You can try with strcmp(string1,string2) function.I thing here problem with
I am trying build a simple registration form with validation. When I leave a field blank and submit my form I keep getting this error undefined index email or undefined index password.For eg I fill in all fields except lastname I will get a notice saying email is undefined and if i fill all the fields I get username ,email and password is undefined. I googled it and the sugesstions i could get was isset , I tried using isset but it still does not work. Can anyone please help?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sign Up</title>
<style>
label{
width:100px;
float:left;
}
</style>
</head>
<body>
<?php
session_start();
$Firstname=isset($_SESSION['Firstname']);
$Lastname=isset($_SESSION['Lastname']);
$username=isset($_SESSION['username']);
$email=isset($_SESSION['email']);
$password=isset($_SESSION['password']);
if(isset($_SESSION['error']))
{
echo '<p>'.$_SESSION['error']['Firstname'].'</p>';
echo '<p>'.$_SESSION['error']['Lastname'].'</p>';
echo '<p>'.$_SESSION['error']['username'].'</p>';
echo '<p>'.$_SESSION['error']['email'].'</p>';
echo '<p>'.$_SESSION['error']['password'].'</p>';
unset($_SESSION['error']);
}
?>
<div class="signup_form">
<form action="registerUser.php" method="post" >
<p>
<label for="Firstname">First Name:</label>
<input name="Firstname" type="text" id="Firstname" size="30"/>
</p>
<p>
<label for="Lastname">Last Name:</label>
<input name="Firstname" type="text" id="Lastname" size="30"/>
</p>
<p>
<label for="username">User Name:</label>
<input name="username" type="text" id="username" size="30"/>
</p>
<p>
<label for="email">E-mail:</label>
<input name="email" type="text" id="email" size="30"/>
</p>
<p>
<label for="password">Password:</label>
<input name="password" type="password" id="password" size="30 "/>
</p>
<p>
<input name="submit" type="submit" value="Submit"/>
</p>
</form>
</div>
<p>Login</p>
</body>
</html>
Here is registeruser.php
<?php
session_start();
include('dbconnect.php');
if(isset($_POST['submit']))
{
//whether the username is blank
if($_POST['FirstName'] == '')
{
$_SESSION['error']['Firstname'] = " FirstName is required.";
}
if($_POST['LastName'] == '')
{
$_SESSION['error']['Lastname'] = " LastName is required.";
}
//whether the email is blank
if($_POST['email'] == '')
{
$_SESSION['error']['email'] = "E-mail is required.";
}
else
{
//whether the email format is correct
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['email']))
{
//if it has the correct format whether the email has already exist
$email= $_POST['email'];
$personcon=$conn;
$sql1 = "SELECT * FROM TBLUSERS WHERE email = '$email'";
$personinfo=oci_parse($personcon,$sql1);
oci_execute($personinfo);
oci_free_statement($personinfo);
if (oci_num_rows($personinfo) > 0)
{
$_SESSION['error']['email'] = "This Email is already used.";
}
}
else
{
//this error will set if the email format is not correct
$_SESSION['error']['email'] = "Your email is not valid.";
}
}
//whether the password is blank
if($_POST['password'] == '')
{
$_SESSION['error']['password'] = "Password is required.";
}
if($_POST['username'] == '')
{
$_SESSION['error']['username'] = "username is required.";
}
if(isset($_SESSION['error']))
{
header("Location: index.php");
exit;
}
else
{
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$email = $_POST['email'];
$username=$_POST['$username'];
$password = $_POST['password'];
$sql2 = "INSERT INTO TBLUSERS (FirstName,LastName,email, username,password) VALUES ('$FirstName', $LastName, '$email', '$username','$password')";
$personinfo2=oci_parse($personcon,$sql2);
oci_execute($personinfo2);
oci_free_statement($personinfo2);
if($personinfo2)
{
/* $from=praveen.mohan#students.mq.edu.au */
$to = $email;
$subject = "Confirmation from TutsforWeb to $username";
$header = "TutsforWeb: Confirmation from TutsforWeb";
$message = "Please click the link below to verify and activate your account. rn";
$sentmail = mail($to,$subject,$message,$header);
if($sentmail)
{
echo "Your Confirmation link Has Been Sent To Your Email Address.";
}
else
{
echo "Cannot send Confirmation link to your e-mail address";
}
oci_close($personcon);
}
}
}
?>
When you do not fill a field, its index will not exist in the $_POST associative array. You need to check with isset whether it exists like this:
<?php
session_start();
include('dbconnect.php');
$_SESSION['error'] = array();
if(isset($_POST['submit'])) {
//whether the username is blank
if((!isset($_POST['FirstName'])) || ($_POST['FirstName'] == '')) {
$_SESSION['error']['Firstname'] = " FirstName is required.";
if((!isset($_POST['LastName'])) || ($_POST['LastName'] == '')) {
$_SESSION['error']['Lastname'] = " LastName is required.";
if((!isset($_POST['email'])) || ($_POST['email'] == '')) {
$_SESSION['error']['email'] = "E-mail is required.";
} else {
//whether the email format is correct
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['email'])) {
//if it has the correct format whether the email has already exist
$email= $_POST['email'];
$personcon=$conn;
$sql1 = "SELECT * FROM TBLUSERS WHERE email = '$email'";
$personinfo=oci_parse($personcon,$sql1);
oci_execute($personinfo);
oci_free_statement($personinfo);
if (oci_num_rows($personinfo) > 0) {
$_SESSION['error']['email'] = "This Email is already used.";
}
} else {
//this error will set if the email format is not correct
$_SESSION['error']['email'] = "Your email is not valid.";
}
}
//whether the password is blank
if((!isset($_POST['password'])) || ($_POST['password'] == '')) {
$_SESSION['error']['password'] = "Password is required.";
}
if((!isset($_POST['username'])) || ($_POST['username'] == '')) {
$_SESSION['error']['username'] = "username is required.";
}
if(isset($_SESSION['error'])) {
header("Location: index.php");
exit;
} else {
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$email = $_POST['email'];
$username=$_POST['$username'];
$password = $_POST['password'];
$sql2 = "INSERT INTO TBLUSERS (FirstName,LastName,email, username,password) VALUES ('$FirstName', $LastName, '$email', '$username','$password')";
$personinfo2=oci_parse($personcon,$sql2);
oci_execute($personinfo2);
oci_free_statement($personinfo2);
if($personinfo2) {
/* $from=praveen.mohan#students.mq.edu.au */
$to = $email;
$subject = "Confirmation from TutsforWeb to $username";
$header = "TutsforWeb: Confirmation from TutsforWeb";
$message = "Please click the link below to verify and activate your account. rn";
$sentmail = mail($to,$subject,$message,$header);
if($sentmail) {
echo "Your Confirmation link Has Been Sent To Your Email Address.";
} else {
echo "Cannot send Confirmation link to your e-mail address";
}
oci_close($personcon);
}
}
}
?>
For example
((!isset($_POST['FirstName'])) || ($_POST['FirstName'] == ''))
will be true if there is no 'FirstName' in $_POST or it is an empty string. The trick is that the second operand will not be checked if the first is true, preventing the problem you have mentioned in the question.
Further observations:
your code assumes that there is a $_SESSION['error'] element. You might get errors if this is not properly initialized
your code is vulnerable to SQL injection
your code is not properly structured, which makes it difficult to maintain
your code mixes up sql with php, which is not elegant
The first issue is that your HTML input names don't match the PHP names you expect.
if($_POST['FirstName'] == '') //Upper case N
While in the markup you use <input name = "Firstname" ... with lower case N
Another issue with the markup is two inputs are named Firstname:
<label for="Lastname">Last Name:</label>
<input name="Firstname" type="text" id="Lastname" size="30"/> <!--Firstname should be Lastname-->
Finally one more problem lies within the index.php file where you try to flash the session variable which comes back from the registerUser.php. Either there should be only one $SESSION["error"] or isset(SESSION["error"]["field"]) must be used just like with the $POST["field"] in registerUser.php.
The flashing code would look like this after the change:
if(isset($_SESSION['error']))
{
if (isset($_SESSION['error']['Firstname'])) echo '<p>'.$_SESSION['error']['Firstname'].'</p>';
if (isset($_SESSION['error']['Lastname'])) echo '<p>'.$_SESSION['error']['Lastname'].'</p>';
if (isset($_SESSION['error']['username'])) echo '<p>'.$_SESSION['error']['username'].'</p>';
if (isset($_SESSION['error']['email'])) echo '<p>'.$_SESSION['error']['email'].'</p>';
if (isset($_SESSION['error']['password'])) echo '<p>'.$_SESSION['error']['password'].'</p>';
unset($_SESSION['error']);
}
I would also suggest looking up a good resource on the topic. Login/Register systems are hard to get right for the first time.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color:red;}
</style>
</head>
<body>
<?php
$username = $password = $email = "";
$usernameerr = $passworderr = $emailerr = "";
if ($_SERVER["REQUEST_METHOD"]=="POST") {
if (empty($_POST["username"])) {
$usernameerr = "Please fill username";
} else {
$username = test_input($_POST["username"]);
if(!preg_match("/^[a-zA-Z]*$/",$username)) {
$usernameerr = "Only letters allowed";
}
}
if (empty($_POST["email"])) {
$emailerr = "Please fill e-mail";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$emailerr = "not a valid e-mail";
}
}
if (empty($_POST["password"])) {
$passworderr = "Cannot be blank";
} else {
$password = test_input($_POST["password"]);
if(!preg_match("/^[a-zA-Z]*$/",$password)) {
$pasworderr = "Must be Letters";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$con = mysqli_connect('localhost','root','','my_db');
if (mysqli_connect_errno()) {
echo "Fail to connect :".mysqli_connect_error();
}
$username = mysqli_real_escape_string($con, $_POST["username"]);
$password = mysqli_real_escape_string($con, $_POST["password"]);
$email = mysqli_real_escape_string($con, $_POST["email"]);
$sql = "INSERT INTO register(Username, Password, Email)
VALUES ('$username','$password','$email')";
if (!mysqli_query($con,$sql)) {
die ('Error: '.mysqli_error($con));
}
echo "Registration successful";
mysqli_close($con);
?>
<h2>Register</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Username :<input type="text" name="username" value="<?php echo $username;?>">
<span class="error">*<?php echo $usernameerr;?></span>
<br><br>
Password :<input type="text" name="password" value="<?php echo $password;?>">
<span class="error">*<?php echo $passworderr;?></span>
<br><br>
E-mail :<input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailerr;?></span>
<br><br>
<input type="submit" value="submit" name="submit">
</form>
</body>
</html>
Hi, I am a newbie, and I need advice on making registration form. So here is the code for my registration form, the validation code works and it submit data to mysql database too. But, the problem is, it will submit data to database every time it loads (even if it is blank). What line of codes should I add to prevent the form submitting data when it is not filled completely / filled with the right format.
Thx in advance.
You have to check if there's any data in the fields.
Just add this line before your sql executes, after $email = mysqli_real_escape_string($con, $_POST["email"]); :
if ($username != "" && $password != "" && $email != "")
{
//your sql and rest of the script goes here
}
else
{
//don't save the data if it's not completed well
//do whatever you want in that case no valid data was completed
}
Notes: I answered only to your question but be careful, you have some implementation mistakes. You should just use a flag that by default is 1 and, if an error is found in any of your validation functions, the falg should be set to 0 and you should check the value of the flag before the sql instead of checking the content of the $_POST variables again.
Edit: BETTER SOLUTION FOR YOUR CODE
Add this block before the sql:
if ($usernameerr == "" && $passworderr == "" && $emailerr == "")
{
//no errors, all fine we can add to the database
}
else
{
//we have errors, do something but don't add the data
}
Please outsource your DB-Connection and your DB-Insert in some seperate files and speak to them per ajax-request..
your db-insert-query should be taken place after you validation and at the end of the
if ($_SERVER["REQUEST_METHOD"]=="POST") {
block
You did not close the $_SERVER["REQUEST_METHOD"]=="POST" block properly.
Also inside the if ($_SERVER["REQUEST_METHOD"]=="POST") { block you can add another
if condition as if(!empty($_POST["username"] && !empty($_POST["email"] && !empty($_POST["password"]) {....}