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

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");
}
}

Related

php redirect to another page after validation

I am trying to figure out how to redirect after validation of a form (i.e after conditions for my form have been met)(I have the header at the end of the PHP code). I have a basic form ,and I know this should be a straightforward code of line but I can't seem to make it work! Your advice is very much appreciated!
<?php
$firstNameErr = '';
$lastNameErr = '';
$emailErr='';
$passwordErr = '';
$passwordConfErr='';
if($_SERVER["REQUEST_METHOD"] == "POST"){
$firstName = $_POST["firstName"];
if(empty($firstName)){
$firstNameErr = "First Name is required";
}
else if(!preg_match("/^[a-zA-Z]+$/", $firstName)){
$firstNameErr= "Only letters, no spaces or special characters allowed";
}
else{
$firstNameErr = "Valid";
}
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$lastName = $_POST["lastName"];
if(empty($lastName)){
$lastNameErr = "Last Name is required";
}
else if(!preg_match("/^[A-Za-z]+((\s)?((\'|\-|)?([A-Za-z])+))*$/", $lastName)){
$lastNameErr = "No Special characters or numbers allowed";
}
else{
$lastNameErr = "Valid";
}
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$email = $_POST["email"];
if(empty($email)){
$emailErr = "Email is required";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
else{
$emailErr = "Valid";
}
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$password=$_POST["password"];
if(empty($password)){
$passwordErr = "Please Enter your password";
}
else if (strlen($password) < "8") {
$passwordErr = "Your Password Must Contain At Least 8 Digits !";
}
else if(!preg_match("#[0-9]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Number !";
}
else if(!preg_match("#[A-Z]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Capital Letter !";
}
else if(!preg_match("#[a-z]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Lowercase Letter !";
}
else if(!preg_match('/[\'^£$%&*()}{##~?><>,|=_+¬-]/', $password)) {
$passwordErr = "Your Password Must Contain At Least 1 Special Character !";
}
else{
$passwordErr = "Valid";
}
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$confirmPassword = $_POST["confirmPassword"];
$password = $_POST["password"];
if(empty($confirmPassword)){
$passwordConfErr = "Please Enter your password";
}
else if($password!=$confirmPassword){
$passwordConfErr = "Passwords do not match";
}
else{
$passwordConfErr="Valid";
}
}
else{
echo "Form not submitted with POST";
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_POST['Register']) and $firstNameErr == "Valid" and $lastNameErr =="Valid" and $emailErr == "Valid" and $passwordErr == "Valid" and $passwordConfErr=="Valid") {
header("Location: profile.php");
exit();
}
}
A single if ($_SERVER["REQUEST_METHOD"] == "POST"){ which wraps all $_POST logic would suffice, then depending on your app (if its mostly AJAX) you should use a response/request flow so the POST logic is at the top and it falls through to the view with the errors which can then be used in the view, or you should return JSON and do an AJAX request, else you won't be able to pick up the errors unless you put them into the session and then pick them up on redirect which is just extra steps.
Example request/response, for a single page i.e register.php, this could be broken out where you load the HTML via an include or view loader but the idea is the same.
<?php
$errors = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// first name
if (empty($_POST["firstName"])){
$errors['firstName'] = "First Name is required";
} else if (!preg_match("/^[a-zA-Z]+$/", $_POST["firstName"])) {
$errors['firstName'] = "Only letters, no spaces or special characters allowed";
}
// last name
if (empty($_POST["lastName"])) {
$errors['lastName'] = "Last Name is required";
} else if (!preg_match("/^[A-Za-z]+((\s)?((\'|\-|)?([A-Za-z])+))*$/", $_POST["lastName"])) {
$errors['lastName'] = "No Special characters or numbers allowed";
}
// ...others
// errors is empty, so must all be valid
if (empty($errors)) {
// do something like insert into db and set session status
header("Location: profile.php");
exit();
}
// otherwise continue to form
} ?>
<form>
...
<input name="firstName" value="<?= htmlspecialchars($_POST['firstName'] ?? '', ENT_QUOTES, 'UTF-8') ?>"/>
<?= isset($errors['firstName']) ? '<span class="form-error">'.$errors['firstName'].'</span>' : '' ?>
<input name="lastName" value="<?= htmlspecialchars($_POST['lastName'] ?? '', ENT_QUOTES, 'UTF-8') ?>"/>
<?= isset($errors['lastName']) ? '<span class="form-error">'.$errors['lastName'].'</span>' : '' ?>
</form>
Or if your going to use mostly AJAX, another way would be to return JSON, then you can access the errors to then build out the dom from the AJAX response.
<?php
//
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
// set json response header
header('Content-type: application/json;charset=utf-8');
// Is POST
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//
$errors = [];
// first name
if (empty($_POST["firstName"])){
$errors['firstName'] = "First Name is required";
} else if (!preg_match("/^[a-zA-Z]+$/", $_POST["firstName"])) {
$errors['firstName'] = "Only letters, no spaces or special characters allowed";
}
// last name
if (empty($_POST["lastName"])) {
$errors['lastName'] = "Last Name is required";
} else if (!preg_match("/^[A-Za-z]+((\s)?((\'|\-|)?([A-Za-z])+))*$/", $_POST["lastName"])) {
$errors['lastName'] = "No Special characters or numbers allowed";
}
// ...others
// errors is empty, so must all be valid
if (empty($errors)) {
// do something like insert into db and set session status
echo json_encode(['status' => 200]);
exit();
}
echo json_encode(['errors' => $errors]);
exit();
} else {
header($_SERVER["SERVER_PROTOCOL"]." 405 Method Not Allowed", true, 405);
echo json_encode(['status' => 405]);
}
} else {
header('Location: /');
}
In both examples, use a single errors array then its easy to access and all in one place. You also don't need to set additional vars from the $_POST['...'] vars to validate them.
Your validating code should look like this:
$Name = $Surname = $username = $password = $confirm_password =
$email ="";
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate Name.
if (empty(trim($_POST["firstName"]))) {
$errors[] = 'name required.';
} else {
$Name = $_POST["firstName"];
}
// Validate lastName.
if (empty(trim($_POST["lastName"]))) {
$errors[] = 'surname required.';
} else {
$Surname = $_POST["lastName"];
}
// Validate username
if (!preg_match("/^[a-zA-Z]+$/", $_POST["username"])) {
$errors['username'] = "Only letters, no spaces or special characters allowed";
}
// Validate username from database to see if username already exist.
//You can check for the email is well.
if(empty(trim($_POST["username"]))){
$errors[] = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT id FROM users WHERE username = :username";
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":username", $param_username, PDO::PARAM_STR);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
if($stmt->rowCount() == 1){
$errors[] = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
$stmt->closeCursor();
}
}
// Validate password
if(empty(trim($_POST["password"]))){
$errors[] = "Enter password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$errors[] = "password should be min 6 characters.";
} else{
$password = trim($_POST["password"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$errors[] = "confirm pass.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if($password != $confirm_password){
$errors[] = "pass no matches.";
}
}
// Validate Email
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
$email = $_POST["email"];
} else {
$errors[] = "invalid email type.";
}
// Validate Email
if(empty(trim($_POST["email"]))){
$errors[] = 'email required.';
}else {
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
}
if(empty($errors)){
//if no errors
//Do everythin else in here
//Do insert query after you are done redirect to profile page
header("Location: profile.php");
exit();
}
}
To get eroors :
<?php if(isset($errors)) {?>
<div class="error">
<?php echo implode('<br/>', $errors); ?>
</div>
<?php } unset($_SESSION['errors']); ?>
And your html form here if its in same page :
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
//inputs etc..
</form>

How to put my validation block of codes into Function PHP

How can I put my validation codes into a function? How am I going to return it and call it? I am trying to call put them in just one code and then call them in a function for my forms. Any idea?
Here's my codes:
function validate(){
$errors = array();
//empty array to collect errors
//VALIDATION CODES (NEED TO BE INSIDE A FUNCTION)
if(empty($_POST['email']) AND filter_var($email, FILTER_VALIDATE_EMAIL) != false)
{
$errors[] = "email cannot be blank";
}
if(empty($_POST['first_name']))
{
$errors[] = "First Name cannot be blank";
}
if(empty($_POST['last_name']))
{
$errors[] = "Last Name cannot be blank";
}
if(empty($_POST['password']))
{
$errors[] = "Password cannot be blank";
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
$errors[] = "Please enter matching password";
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
$errors[] = "Please enter matching password";
}
if(!isset($_POST['date']) || strtotime($_POST['date']) === false)
{
$errors[] = "Birth Date cannot be blank";
}
if(!empty($errors))
{
//if there are errors, assign the session variable!
$_SESSION['errors'] = $errors;
//redirect your user back using header('location: ')
header('Location: registration_page.php');
}
else
{
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$password = $_POST['password'];
$birth_date = $_POST['date'];
//redirect your user to the next part of the site!
}
}
So when I call this this wont work:
echo validate();
Hope you can help. Thanks!
So you're saying something like:
class Validation {
public static function emailFilter($input) {
global $_POST;
return empty($_POST['email']) AND filter_var($input,
FILTER_VALIDATE_EMAIL) != false ? "email cannot be blank" : false;
}
}
Or are you looking to do something else?
EDIT 1
Okay, how about:
function filter ($input, $type) {
if (!$input OR !$type) {
switch ($type) {
case "email":
// Check email
if (empty($_POST['email']) AND filter_var($input, FILTER_VALIDATE_EMAIL)) {
return "email cannot be blank";
}
break;
case "first_name":
if(empty($_POST['first_name']))
{
return "First Name cannot be blank";
}
break;
// And so on.
}
}
}
You could call it then by:
filter($_POST['email'], 'email');
So then:
if (!filter($_POST['email'], 'email')) {
// The email checks out.
} else {
$error[] = filter($_POST['email'], 'email');
}
There are will be more elegant solutions available, but this is based on what I think you want.
Let's say that the user clicks the button after filling-up the required fields, in your $_POST['submit'] or whatever name of your button, just add your codes, and print the error beside the html textbox by adding or if you want, just print $error below the textboxes of your html registration page. And if the errors return zero value, then you can add everything in the database then redirect to your desired page in the else block of your error checking codes.
I would do this like so:
function validate(){
$errors = array();
//empty array to collect errors
//VALIDATION CODES (NEED TO BE INSIDE A FUNCTION)
if(empty($_POST['email']) AND filter_var($email, FILTER_VALIDATE_EMAIL) != false)
{
array_push($errors, "Email cannot be blank");
}
if(empty($_POST['first_name']))
{
array_push($errors, "First Name cannot be blank");
}
if(empty($_POST['last_name']))
{
array_push($errors, "Last Name cannot be blank");
}
if(empty($_POST['password']))
{
array_push($errors, "Password cannot be blank");
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
array_push($errors, "Please enter matching password");
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
array_push($errors, "Please enter matching password");
}
if(!isset($_POST['date']) || strtotime($_POST['date']) === false)
{
array_push($errors, "Birth Date cannot be blank");
}
if(!empty($errors))
{
//if there are errors, assign the session variable!
$_SESSION['errors'] = implode("|", $errors);
//redirect your user back using header('location: ')
return 0;
/*
Can't use both return & redirect, but return is more flexible.
*/
//header('Location: registration_page.php');
}
else
{
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$password = $_POST['password'];
$birth_date = $_POST['date'];
return array("email" => $email, "first_name" => $first_name,
"last_name" => $last_name, "password" => $password,
"birth_date" => $birth_date);
// so now you have your results in an associative array.
// you can use print_r(validate()); to see the results, or use
// $r = validate(); if ($r != false) { /*go places!*/}
//redirect your user to the next part of the site!
}
}

FILTER_VALIDATE_EMAIL not working

I certainly must be missing something here. For some reason filter_var is not working. I'm trying to validate an email from $_POST, and it returns false even with valid emails. But, when I hardcode an email, it works fine. What's wrong?
Here's my php code:
function redirect() { //redirecting to home page function. Used in one of the lectures.
$host = $_SERVER["HTTP_HOST"];
$path = rtrim(dirname($_SERVER["PHP_SELF"]), "/\\");
header("Location: http://$host$path/index.php");
exit;
}
try
{
$dbh = new PDO($db, $dbuser, $dbpassword);
}
catch (PDOException $e)
{
echo "Connection failure: " . $e->getmessage();
}
if (!isset($_POST['email']) || !isset($_POST['password1']) || !isset($_POST['password2'])) {
redirect();
}
$password1 = htmlspecialchars($_POST['password1']);
$email = htmlspecialchars($_POST['email']);
$password2 = htmlspecialchars($_POST['password2']);
//preg_match('/.+#.+\./', $email) == FALSE
if ($email = "") {
print "email not there";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
print "not real email";
} elseif (strlen($password1) < 6) {
print("password too small");
} elseif (!(preg_match('/[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/', $password1))) {
print "numbers and letters plz";
} elseif ($password1 != $password2) {
print "passwords not same";
//redirect();
}
Change the first email check:
if ($email == "") {
print "email not there";
}
It is getting the value " instead of checking for it.

If/else statements in PHP and Ajax input validation

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....

Find out which the user filled out

I'm trying to figure out how to find out where I need to do the steps if it was the username or if it was the email address the user filed out.
// Assign variable values if there is values
if ((isset($_POST['username'])) && ($_POST['username'] !== NULL) && (!empty($_POST['username']))) { $username = trim($_POST['username']); }
if ((isset($_POST['email'])) && ($_POST['email'] !== NULL) && (!empty($_POST['email']))) { $email = trim($_POST['email']); }
// IF BOTH FIELDS ARE EMPTY, ERROR CONDITION EXISTS
if (empty($username) && empty($email)) {
$errors = "yes";
$message = "You must enter a value for either the username or email address!";
$output = array('errorsExist' => true, 'message' => $message);
} else if (!empty($username) && !empty($email)) {
$errors = "yes";
$message = "You can only enter a value for the username or email address!";
$output = array('errorsExist' => true, 'message' => $message);
} else {
}
// Assign variable values if there is values
if ((isset($_POST['username'])) && ($_POST['username'] !== NULL) && (!empty($_POST['username']))) { $username = trim($_POST['username']); }
if ((isset($_POST['email'])) && ($_POST['email'] !== NULL) && (!empty($_POST['email']))) { $email = trim($_POST['email']); }
// IF BOTH FIELDS ARE EMPTY, ERROR CONDITION EXISTS
if (empty($username) && empty($email)) {
$errors = "yes";
$message = "You must enter a value for either the username or email address!";
$output = array('errorsExist' => true, 'message' => $message);
} else if (!empty($username) && !empty($email)) {
$errors = "yes";
$message = "You can only enter a value for the username or email address!";
$output = array('errorsExist' => true, 'message' => $message);
} else {
if(!empty($username)) {
//Do some things if the user entered only the username
}
else {
//Do some things if the user entered only email
}
}
else if ( empty( $username ) ) {
// Output username error
}
else if ( empty( $email ) ) {
// Output email error
}
In this case, however, I would skip the if/else statements, and just use an error condition:
$is_error = false;
if ( empty( $username ) ) {
$is_error = true;
$error_messages[] = 'Your username error message';
}
if ( empty( $email ) ) {
$is_error = true;
$error_messages[] = 'Your email error message';
}
if ( $is_error ) {
// Output all error messages
}
else {
// Perform success event
}
I think you need to do your steps in the last else that will execute only if neither username and email are empty or inputted. So in the last else, you can do something like
if (!empty($username)) {
} else {
}
On another note, I think you do not need to all the 3 checks when populating $username or $email; the first and the last should suffice, like:
if (isset($_POST['username']) && !empty($_POST['username']) {
$username = $_POST['username'];
}

Categories