If/else statements in PHP and Ajax input validation - php

I'm sending some data by Ajax to a PHP script, which handles registration. I'm trying to get a response from the server whether an input is valid or not (live validation). I want each input to have its own response, that means if the first input is still invalid and someone puts something invalid in the second input field, the first response stays and it also sends the second response.
What now happens is this: First input is invalid, I see the response, but when I go the next input field and put something invalid in the field, the first response just stays there.(I have tested this with console.log in Chrome)
UPDATE: to give an example, I'm seeing this: not a valid username!and then I put some invalid email address in the next field and I still see not a valid username!.
This is my PHP code:
if(isset($_POST['username']) && isset($_POST['email']) && isset($_POST['email2']) && isset($_POST['password'])
&& isset($_POST['firstname']) && isset($_POST['surname']) && isset($_POST['gender']) && isset($_POST['day'])
&& isset($_POST['month']) && isset($_POST['year']) ) {
$username = $_POST['username'];
$email = $_POST['email'];
$email2 = $_POST['email2'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
$gender = $_POST['gender'];
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
if(!preg_match("/^[a-z](?=[\w.]{3,19}$)\w*\.?\w*$/i",$username)){
echo "not a valid username.";
}
else if(filter_var($email,FILTER_VALIDATE_EMAIL)){
echo "OK!";
}
else if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
echo "not a valid email address";
}
else if(strcmp($email,$email2) != 0){
echo "emails are different.";
}
else if(strcmp($email,$email2) == 0){
echo "OK!";
}
else if(!preg_match("[a-zA-Z]*",$firstname)){
echo "Not a valid firstname.";
}
else if(preg_match("[a-zA-Z]*",$firstname)){
echo "OK!";
}
else if(!preg_match("[a-zA-Z]*",$surname)){
echo "not a valid surname.";
}
else if(preg_match("[a-zA-Z]*",$surname)){
echo "OK!";
}
}
and this is the JQuery Ajax code:
function handlePost() {
var username = $('#username').val();
var email = $('#email').val();
var email2 = $('#email2').val();
var password = $('#password').val();
var firstname = $('#firstname').val();
var surname = $('#surname').val();
var gender = $('#gender').val();
var day = $('#day').val();
var month = convertMonth($('#month').val())
var year = $('#year').val();
$.ajax({
type: "POST",
url: "handleRegister.php",
data: "username="+username+"&email="+email+"&email2="+email2+"&password="+password+"&firstname="
+firstname+"&surname="+surname+"&gender="+gender+"&day="+day+"&month="+month+"&year="+year,
success: function(resp){
// we have the response
//alert("Server said:\n '" + resp + "'");
console.log("Server said:\n '" + resp + "'")
},
error: function(e){
//alert('Error: ' + e);
console.log("Server said:\n '" + e + "'")
}
});
}
I would think it's the way I'm using if/else here. Also I'm a little confused about how/when to use isset($_POST['submit']) in this case?
Thanks in advance.

Change some of your else ifs into ifs. Using just else if, as soon as a condition matches the rest are skipped. So when you have an invalid username, your code never checks to see if the email is valid or not.
Only use else if when you want ONLY ONE of the outputs.

$errors = array();
if (!preg_match("/^[a-z](?=[\w.]{3,19}$)\w*\.?\w*$/i", $username))
{
$errors[] = "not a valid username.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$errors[] = "not a valid email address";
}
if ($email !== $email2)
{
$errors[] = "emails are different";
}
if (!preg_match("[a-zA-Z]*", $firstname))
{
$errors[] = "Not a valid firstname.";
}
if (!preg_match("[a-zA-Z]*", $surname))
{
$errors[] = "not a valid surname.";
}
if ($errors)
{
echo implode("\n", $errors);
}
else
{
echo 'OK!';
}

What you would want to do is, instead of elses, just ifs like:
if(!preg_match("/^[a-z](?=[\w.]{3,19}$)\w*\.?\w*$/i",$username)){
echo "not a valid username.";
}
if(filter_var($email,FILTER_VALIDATE_EMAIL)){
echo "OK!";
}
if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
echo "not a valid email address";
}
if(strcmp($email,$email2) != 0){
echo "emails are different.";
}
etc....

Related

PHP Sign-up Form Issues with Validation and Insertion

I'm looking to create a sign-up page for a large-scale website which means I'm using a lot more layers of validation then I would normally do, given this should be common practice but in this particular case more than any other situation it is imperative.
I've already written most of the code required and formatted it in an order which I believed wouldn't lead to any undefined variable errors, however, upon form submission it doesn't create a new SQL row and doesn't return any errors under the error handling areas of the form validation. In all fairness, the error handling is quite simple at this point and is not a final version, just what I put in place to help me debug and troubleshoot any issues which should arise.
Here's the PHP code, and the snippet of the piss-poor error handling that is supposed to output an error message if an error occurs, to re-state, this error handling isn't final.
$conn = mysqli_connect('localhost', 'root2', '123', 'db');
$signupConditionsMet = "0";
if (isset($_POST["email"]) && isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["passwordCheck"]) && isset($_POST["birthdate"])) {
$signupConditionsMet = "1";
$birthGood = true;
$passGood = false;
$nameGood = false;
$emailGood = false;
}
$usernameSearch = $conn->prepare("SELECT * FROM users WHERE username = ?");
$userInsertion = $conn->prepare("INSERT INTO users (username, passwd, birthdate, email) VALUES (?,?,?,?)");
$nameErr = $emailErr = $passErr = $birthErr = "";
$name = $email = $pass = $birth = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["username"];
$email = $_POST["email"];
$pass = $_POST["password"];
$birthdate = $_POST["birthdate"];
$passCheck = $_POST["passwordCheck"];
}
if ($signupConditionsMet === "1"){
function test_input($name) {
if (!preg_match("/^[a-z\d_]{2,15}$/i",$name)) {
$nameErr = "Only letters and white space allowed";
} else {
$nameGood = true;
return $name;
echo "did name ez";
}
}
function test_input2($email){
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
} else {
$emailGood = true;
return $email;
echo "did email ez";
}
}
function test_input3($password){
if (!preg_match("/^[a-z\d_]{2,15}$/",$pass)) {
$passErr = "Invalid password format";
} else if (!preg_match("/^[a-z\d_]{2,15}$/",$passCheck)){
$passErr = "Invalid password check format";
} else if ($_POST["password"] !== $_POST["passwordCheck"]){
$passErr = "Passwords do not match";
} else {
$passwd2 = AES_ENCRYPT($_POST["password"], 'mysecretstring');
$passwdGood = true;
return $passwd2;
echo "did pass ez";
}
}
}
if (($signupConditionsMet === "1") && ($birthGood === true) && ($nameGood === true) && ($passwdGood === true) && ($emailGood === true)) {
if ($usernameSearch->execute(array($_POST['username']))) {
while ($row = $usernameSearch->fetch()) {
if (!empty($row['id'])) {
$creationError = "This username is already taken";
} else {
$userInsertion->bindParam(1, $name);
$userInsertion->bindParam(2, $passwd2);
$userInsertion->bindParam(3, $birthdate);
$userInsertion->bindParam(4, $email);
$userInsertion->execute();
header('Location: userlanding.php');
}
}
}
}
/* PHP inside the HTML to output errors */
<?php if ($signupConditionsMet === "1") { echo "all inputs received"; echo $_SERVER["REQUEST_METHOD"];} else { echo "drats, they weren't all there"; echo $name; echo $email; echo $birthdate; echo $pass; echo $passCheck;}?>
<?php if ($passErr) { echo $passErr;} else if ($nameErr) { echo $nameErr;} else if ($emailErr) { echo $emailErr;} else if ($birthErr) { echo $birthErr;} ?>
Disregarding the previously admitted terrible error handling, I can't seem to wrap my head around why it doesn't work in its current form. It returns (from the client-side reporting) that all inputs were received and there isn't any fatal errors thrown from running the PHP code. In addition, the second client-side code which prints any errors doesn't print anything either, implying that all functions operated correctly, however, the echos at the bottom of the input tests don't echo the strings they've been assigned, implying those didn't work, but there was no errors. Hmm. Perhaps I'm missing something blatantly obvious regarding my syntax but I don't see why it wouldn't work. Any help would be appreciated.

Is this possible to send response back to page by doing some if/else in ajax

I want to know that is this possible to send response back by using some if/else on response we get from server under success in $.ajax..
ajax
$.ajax({
url : "request/register.php",
type : "POST",
data : 'firstName='+firstName + '&lastName='+lastName + '&userName='+userName + '&email='+email + '&password='+password + '&con_password='+con_password,
dataType : "text",
beforeSend : function(http){
$('#reg').val("Submitting....");
},
success : function(response,status,http){
var text = response;
alert(text);
if(text != "<span class=\"error\" data-icon =''>Empty Fields</span>"){
alert("Done");
}else{
alert("oOps")
}
},
error : function(http,status,error){
alert('server error');
}
})
registeration.php
//creating a variable for error messages
$error = "";
//creating a variable for success messages
$success = "";
//form validation
if($_SERVER['REQUEST_METHOD'] == "POST"){
$firstName = trim(filter_input(INPUT_POST, 'firstName' ,FILTER_SANITIZE_STRING));
$lastName = trim(filter_input(INPUT_POST, 'lastName' ,FILTER_SANITIZE_STRING));
$userName = trim(filter_input(INPUT_POST, 'userName' ,FILTER_SANITIZE_STRING));
$email = trim(filter_input(INPUT_POST, 'email' ,FILTER_SANITIZE_EMAIL));
$password = trim(filter_input(INPUT_POST, 'password' ,FILTER_SANITIZE_STRING));
$confirm_pass = trim(filter_input(INPUT_POST, 'con_password' ,FILTER_SANITIZE_STRING));
//checking for empty feilds
if($firstName == "" || $lastName == "" || $userName == "" || $email == "" || $password == "" || $confirm_pass == ""){
$error = "Empty Fields";
}
//checking username length
if(empty($error) && strlen($userName)<=5){
$error = "Username must be greater than 5 characters";
}
//checking for username existence
if(empty($error) && user_exist($userName)){
$error = "Username already exist";
}
//email validation
if(empty($error) && !filter_var($email,FILTER_VALIDATE_EMAIL)){
print_r($_POST);
$error = "Invalid Email address";
}
//checking for email existence
if(empty($error) && email_exist($email)){
$error = "Email already exist";
}
//checking password length
if(empty($error) && strlen($password)<=8){
$error = "Password must be greater than 8 characters";
}
//matching confirm password
if(empty($error) && $password !== $confirm_pass){
$error = "Password not match";
}
if(empty($error)){
if(user_registration($firstName,$lastName,$userName,$email,md5($password))){
$success = "Registered Suceessfully";
}else{
$error = "Something went wrong";
}
}
}
if(!empty($error)){
echo "<span class=\"error\" data-icon =''>".$error."</span>";
}
if (empty($error) && !empty($success)) {
echo "<span class=\"success\" data-icon =''>".$success."</span>";
}
If response is something like than i want to set input[type="text"] values should be same what user type and input[type="password"] should be blank & in other case if response is something like i want all the input feilds empty..
Yes, it's possible. But as the body may change overtime, it's best to do your if/else logic on the HTTP/1.1 Status Codes.
For example;
In your error response, simply return an error code 400 Bad Request by using http_response_code()
http_response_code(400);
And in your success response, simply return a 201 Created
http_response_code(201);
Now, in your jQuery, you can just look at the return status code and do the appropriate thing for the end-user
//[...]
success : function(response,status,http) {
if(http.status === 201) {
alert("User created");
} else {
//Assume there was an error
//Do some error logging for the end-user
alert("Could not create the user");
}
}

php: best way to validate POST

I have been using the code below to validate my user input by $_POST:
if(isset($_POST['name']) && !empty($_POST['name'])) {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
This code checks whether 'name' was actually set, which is obvious and clear and needed.
Secondly, it checks whether user typed something in textfield to give a value for name.
However, if user gives SPACE " " as input it accepts it because it is not empty it has SPACE.
I found one way of doing it right:
if(isset($_POST['name'])) {
$n = trim($_POST['name']);
if(empty($n)) {
$errors[] = "Please give a name";
}
}
else {
$errors[] = "Please give a name";
}
But here I am repeating same error message twice, so how can it be optimized?
if(isset($_POST['name']) && trim($_POST['name']) !== "") {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
Remove the empty, and just do the trim.
To be honest, you don't even need the isset unless you have notices turned on:
if(trim($_POST['name']) !== "") {
If you don't need the trimmed string, you can move the trim itself to the if-clause:
if(isset($_POST['name']) && (trim($_POST['name']) != '') ) {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
If you further need it, you could modify the input before checking:
$_POST['name'] = trim( $_POST['name'] );
if(isset($_POST['name']) && !empty($_POST['name'])) {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
Try like this
if(trim(isset($_POST['name']))) {
$n = trim($_POST['name']);
}
else {
$errors[] = "Please give a name";
}
try
if(isset($_POST['name'])) {
$n = trim($_POST['name']);
}
if(empty($n) or !isset($_POST['name'])) {
$errors[] = "Please give a name";
}
Just change your above code to this
if(trim(isset($_POST['name'])))
{
$n = trim($_POST['name']);
}
else
{
$errors[] = "Please give a name";
}
Try using this
if(isset($_POST['name']) && trim($_POST['name']) != false) {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
Finally I came to use the following code. It is better because here I can even control minimum number of characters.
if(isset($_POST['name']) && strlen(trim($_POST['name'])) > 1) {
$block->name = trim($_POST['name']);
}
else {
$errors[] = "Please give a name. It should be at least two characters";
}

Why is $_POST['submit'] NULL here?

This $_POST['submit'] is driving me crazy. I don't see any reason why its value is NULL.
This is my PHP code:
if(isset($_POST['username']) && isset($_POST['email']) && isset($_POST['email2']) && isset($_POST['password'])
&& isset($_POST['firstname']) && isset($_POST['surname']) && isset($_POST['gender']) && isset($_POST['day'])
&& isset($_POST['month']) && isset($_POST['year']) ) {
$username = $_POST['username'];
$email = $_POST['email'];
$email2 = $_POST['email2'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
$gender = $_POST['gender'];
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$date = $year."-".$month."-".$day;
$hashed_password = hashMe($password,$salt);
if (!preg_match("/^[a-z](?=[\w.]{3,19}$)\w*\.?\w*$/i", $username)) {
echo "invalid username";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email.";
}
if ($email !== $email2) {
echo "Emails are not matching.";
}
if (!preg_match("/^([^\s])[a-zA-Z]*$/i", $firstname)) {
echo "Invalid first name.";
}
if (!preg_match("/^([^\s])[a-zA-Z]*$/i", $surname)) {
echo "Invalid last name.";
}
if($day === "Day" || $month === "Month" || $year === "Year") {
echo "Choose a date.";
}
if($gender === "Your gender:") {
echo "choose a gender.";
}
else if(array_key_exists('submit', $_POST))
{
$mysqli = new mysqli('blaa', 'blablaa', 'blabla', 'cucumber');
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
$stmt = $mysqli->prepare("INSERT INTO USERS (USER_USERNAME, USER_EMAIL, USER_GENDER, USER_FIRSTNAME, USER_LASTNAME, USER_BIRTHDAY, USER_PASSWORD, USER_SALT) VALUES (?,?,?,?,?,?,?,?)");
$stmt->bind_param('ssssssss',$username,$email,$gender,$firstname,$surname,$date,$hashed_password,$salt);
$stmt->execute();
echo "everything successfully inserted into the database \n";
}
else{
var_dump($_POST['submit']);
echo "something went wrong!";
}
}
And this is my button code:
<input class="btn btn-large btn-success" id="register-button" type="submit" name="submit" value="Registreer" onclick="handlePost()"/>
Useful to know maybe: I've tried reading all log files, nothing there. All other values are being sent to the server nicely, so there's no problem with the rest of the form. handlePost()makes an Ajax call to the server. using var_dump($_POST)I'm getting everything except submit. And var_dump($_POST['submit']) gives me NULL.
UPDATE: handlePost():
function handlePost() {
var username = $('#username').val();
var email = $('#email').val();
var email2 = $('#email2').val();
var password = $('#password').val();
var firstname = $('#firstname').val();
var surname = $('#surname').val();
var gender = $('#gender').val();
var day = $('#day').val();
var month = convertMonth($('#month').val())
console.log(month);
var year = $('#year').val();
$.ajax({
type: "POST",
url: "handleRegister.php",
data: "username="+username+"&email="+email+"&email2="+email2+"&password="+password+"&firstname="
+firstname+"&surname="+surname+"&gender="+gender+"&day="+day+"&month="+month+"&year="+year,
success: function(resp){
// we have the response
//alert("Server said:\n '" + resp + "'");
console.log("Server said:\n '" + resp + "'");
},
error: function(e){
//alert('Error: ' + e);
console.log("Server said:\n '" + e + "'");
}
});
}
I'm not using <form>, so I guess I also have to send 'submit' ?
Your data string does not contain the submit field. If you add it, it should solve your problem.
var sbmt = $('#register-button').val();
and
data: "username="+username+"&email="+email+"&email2="+email2+"&password="+password+"&firstname="
+firstname+"&surname="+surname+"&gender="+gender+"&day="+day+"&month="+month+"&year="+year+"&submit="+sbmt
How does handlePost() make the AJAX call?
I'm of the impression that the submit button value will only be included in the POST data if the event to submit the form comes from the button itself (which is why when you have numerous submit buttons, only the one that was clicked is included in the data).
Edit:
The data property in your $.ajax call must contain everything you want to send to the server; it won't automatically include form values you haven't specified.
Doing an AJAX call is not the same as submitting your form normally, regardless of how it is triggered.

registration form in php

$error1='';
$error2='';
$error3='';
$error4='';
$error5='';
$error6='';
$yourname='';
$email='';
$email2='';
$password='';
$password2='';
$country='';
if (isset($_POST['Registerme']))
{
$_POST['yourname']=$yourname;
$_POST['email']=$email;
$_POST['email2']=$email2;
$_POST['password']=$password;
$_POST['password2']=$password2;
$_POST['country']=$country;
if($yourname==''){
$error1='name required';
}
if($email==''){
$error2='email required';
}
if($email2==''){
$error3='required field';
}
if($password==''){
$error4='password required';
}
if($password2==''){
$error5='required field';
}
if($country==''){
$error6='country required';
}
if(empty($error1) && empty($error2) && empty($error3) && empty($error4) && empty($error5) && empty($error6))
{echo 'mysql query goes here and add the user to database';}
}///main one
else {$error1='';
$error2='';
$error3='';
$error4='';
$error5='';
$error6='';}
this is a registration validation script. in my registration form there are two email and password filelds.second fields are for confirmation.i want to check weather user typed same information in that both field.if i want to do that in this script should i use another if statement? or i should use else if? i am confused about that step...
Some comments:
You MUST sanitize input! Take a look at best method for sanitizing user input with php.
Your assignments: Instead of "$_POST['yourname']=$yourname;" it should be "$yourname=$_POST['yourname'];".
You're using a lot of variables for error control, and after that if all went well you simply forget the error messages in the last else block. Use some kind of array for error strings, and use it!
Are you sure you aren't validating usernames/passwords to not contain spaces or weird characters, or emails to be valid?
Some sample code...:
// Simple sanitize function, complete it
function sanitize_input ($inputstr) {
return trim(mysql_real_escape_string($inputstr));
}
if (isset ($_POST['Registerme']) {
// array of error messages to report
$error_messages = array();
$isvalid = true;
// Assignment
$yourname = sanitize_input ($_POST['yourname']);
$email = sanitize_input ($_POST['email']);
$email2 = sanitize_input ($_POST['email2']);
$password = sanitize_input ($_POST['password']);
$password2 = sanitize_input ($_POST['password2']);
$country = sanitize_input ($_POST['country']);
// Validation
if (empty ($yourname)) {
$error_messages[] = "You must provide an username";
}
if (empty ($password)) {
$error_messages[] = "You must provide a password.";
}
elseif ($password !== $password2) {
$error_messages[] = "Passwords do not match.";
}
// Same for email, you caught the idea
// Finally, execute mysql code if all ok
if (empty($error_messages)) {
// Execute mysql code
isvalid = true;
}
}
// After form processing, use isvalid which is false if there are errors
// and the error_messages array to report errors
add additional conditions to your second if statement.
e.g.
if($email=='' || $email != $email2){
...
Just add simple checks. I wouldn't combine the check with the general password check - as I can imagine you would like to tell the user what went wrong exactly.
if ($password1 !== $password2) {
// Add an specific error saying the passwords do not match.
}
I would replace the user of loose errors to an array like:
$aErrors = array();
if ($password1 !== $password2) {
$aErrors[] = 'Another specific error!';
}
if (empty($password1) || empty($password2)) {
$aErrors[] = 'Another specific error';
}
if (empty($aErrors)) {
// Process the form!
}
There are lots of issues with your code.
1. You are assinging $_POST['key'] = $somevalue, while I think you mean $somevar = $_POST['key']
2. Use an array for all error messages as it'll make your life a bit easier ..
3. To compare password use something like
if ($password1 !== $password2) {
}
so .....
$errors = array();
so you'd check something like ..
if ($password1 !== $password2) {
$errors[] = 'Password dont match';
}
if(count($errors) > 0) { //if there are errors
foreach($errors as $err) {
echo $err.' <br />';
}
} else {
// whatever you want to do if no error
}
I'll also suggest to sanitise the $_POST values before you use them in your queries.
I hope it helps.
I think you mean to do this:
$yourname = $_POST['yourname'];
$email = $_POST['email'];
$email2 = $_POST['email2'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$country = $_POST['country'];
Second this make use of an errors array:
$errors = array();
Third use nested ifs(just a suggestion)
if (!empty($_POST['password1'])) {
if ($_POST['password1'] != $_POST['password2']) {
$errors[] = '<font color="red">The 2 passwords you have entered do not match.</font>';
} else {
$password = $_POST['password1'];
}
} else {
$errors[] = '<font color="red">Please provide a password.</font>';
}

Categories