Find out which the user filled out - php

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'];
}

Related

Wordpress Registration with Email Confirmation

I have created a registration forms with PHP in my Wordpress site.
For now users can create an account and login normally.
But I want to add a function that sends an activation to email before they can login.
This is the current code I have.
<?php
$error= '';
$success = '';
global $wpdb, $PasswordHash, $current_user, $user_ID;
if(isset($_POST['task']) && $_POST['task'] == 'register' ) {
$role_option = $wpdb->escape(trim($_POST['role-option']));
$password1 = $wpdb->escape(trim($_POST['password1']));
$password2 = $wpdb->escape(trim($_POST['password2']));
$first_name = $wpdb->escape(trim($_POST['first_name']));
$last_name = $wpdb->escape(trim($_POST['last_name']));
$email = $wpdb->escape(trim($_POST['email']));
$email2 = $wpdb->escape(trim($_POST['email2']));
$username = $wpdb->escape(trim($_POST['username']));
$userrole = $wpdb->escape(trim($_POST['userrole']));
if( $email == "" || $password1 == "" || $password2 == "" || $username == "" || $first_name == "" || $last_name == "" || $role_option == "") {
$error= 'Please don\'t leave the required fields.';
} else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error= 'Invalid email address.';
} else if(email_exists($email) ) {
$error= 'Email already exist.';
} else if($email <> $email2 ){
$error= 'Emails do not match.';
} else if($password1 <> $password2 ){
$error= 'Password do not match.';
} else {
$user_id = wp_insert_user( array ('first_name' => apply_filters('pre_user_first_name', $first_name), 'last_name' => apply_filters('pre_user_last_name', $last_name), 'user_pass' => apply_filters('pre_user_user_pass', $password1), 'user_login' => apply_filters('pre_user_user_login', $username), 'user_email' => apply_filters('pre_user_user_email', $email), 'role' => apply_filters('pre_user_user_role', $role_option)) );
if( is_wp_error($user_id) ) {
$error= 'Error on user creation.';
} else {
do_action('user_register', $user_id);
$current_url = home_url($_SERVER['REQUEST_URI']);
wp_redirect( $current_url );
exit;
$success = 'You\'re successfully register';
}
}
}
?>

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!
}
}

basic php else if not working

I have some php validation for a user signup form. It's validating all the input then if all is correct the else at the end, checks to see if that username is in use and if not creates that record in the database. For some reason the last else doesn't get activated and it just refreshes with all the data still in the input boxes. I can't find the problem anywhere!!
if(isset($_POST['user']))
{
$firstname = sanitiseString($_POST['firstname']);
$surname = sanitiseString($_POST['surname']);
$user = sanitiseString($_POST['user']);
$pass = sanitiseString($_POST['pass']);
$email = sanitiseString($_POST['email']);
$dateOfBirth = sanitiseString($_POST['dateOfBirth']);
$gender = sanitiseString($_POST['gender']);
$test_arr = explode('-',$dateOfBirth);
if($firstname == "" || $surname =="" || $user == "" || $pass == "" || $email == "" || $dateOfBirth == "" || $gender == "")
{$error = "Not all fields were entered</br></br>";}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{$error = "Email format invalid</br></br>";}
else if(count($test_arr) == 3)
{
if (!checkdate($test_arr[0], $test_arr[1], $test_arr[2]))
{$error = "Enter a date in the format: MM-DD-YYYY</br></br>";}
}
else if(count($test_arr) <> 3)
{$error = "Enter a date in the format: MM-DD-YYYY</br></br>";}
else
{
$result = querySQL("SELECT * FROM members WHERE user='$user'");
if($result->num_rows)
{$error = "That Username already exists</br></br>";}
else
{
querySQL("INSERT INTO members VALUES('','$firstname','$surname','$user','$pass','$email','$dateOfBirth','$gender')");
die("<h4>Account Created</h4>Please Log In.</br></br>");
}
}
}
First thing to comment on is the incredible amount of nested logic this script has; it's not uncommon to lose control of the flow when you're if / else branching gets out of control.
Example Restructure
if (isset($_POST['user']))
{
// Prep
$error = '';
// Sanitize
foreach( $_POST as $varName => $value )
{
// Doing this for minification on Stackoverflow
$$varName = sanitiseString($_POST[$varName]);
// Validate
if ( empty($$varname) )
$error .= "Not all fields were entered<br /><br />";
}
// Valid Email?
if ( !filter_var($email, FILTER_VALIDATE_EMAIL) )
$error .= "Email format invalid<br /><br />";
// Validate date
$dateArray = explode('-', $dateOfBirth);
if (!checkdate($dateArray[0], $dateArray[1], $dateArray[2]))
{
$error .= "Enter a date in the format: MM-DD-YYYY</br></br>";
}
$result = querySQL("SELECT * FROM members WHERE user='$user'");
if ($result->num_rows)
{
$error .= "That Username already exists</br></br>";
}
if ( !empty($error) )
die($error);
querySQL("INSERT INTO members VALUES('','$firstname','$surname','$user','$pass','$email','$dateOfBirth','$gender')");
die("<h4>Account Created</h4>Please Log In.</br></br>");
}
Some other things to note are conflicting logic with your count($test_arr) == 3 and count($test_arr) <> 3. And the value of $result->num_rows may not be 0, as your expecting.

Return only true or false (PHP)

I have this PHP code which should return only either true or false after running multiple stored functions, but unfortunately it does not work as expected.
I firstly check the email validation and return true if valid and false if invalid, then i am doing the same for username.
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Email is valid
if(checkmail($_POST['email'])) {
$_SESSION['v_mail'] = $_POST['email'];
$valid = true;} else { $valid=false; }
// username is valid
if(checkuser($_POST['username'],5,10)) {
$_SESSION['v_username'] = $_POST['username'];
$valid=true;} else { $valid=false; }
}
I need to return only False or True after checking both.
I know that it is very small trick but i could not get it.
Try this:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Email is valid
if(checkmail($_POST['email'])) {
$_SESSION['v_mail'] = $_POST['email'];
$valid = true;} else { $valid=false; }
// username is valid
if(checkuser($_POST['username'],5,10)) {
$_SESSION['v_username'] = $_POST['username'];
} else { $valid=false; } //and between the last $valid value
}
or again this:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Email is valid
if(checkmail($_POST['email'])) {
$_SESSION['v_mail'] = $_POST['email'];
$valid = true;} else {
$valid=false; return} //exit from the function if valid is false
// username is valid
if(checkuser($_POST['username'],5,10)) {
$_SESSION['v_username'] = $_POST['username'];
$valid=true;} else { $valid=false; }
}
if(checkmail($_POST['email']) && checkuser($_POST['username'],5,10)) {
$_SESSION['v_mail'] = $_POST['email'];
$_SESSION['v_username'] = $_POST['username'];
$valid = true;
} else {
$valid = false;
}
Sorry was tired missed part of the code, however I would approach this problem little bit differently:
$isMail = (checkmail($_POST['email'])) ? $_SESSION['v_mail'] = $_POST['email'] : false;
$isUser = (checkuser($_POST['username'],5,10)) ? $_SESSION['v_username'] = $_POST['username'] : false;
$valid = $isMail && $isUser;
Or move $_SESSION variables to checkmail, checkuser functions and then simply $valid = checkmail($_POST['email']) && checkuser($_POST['username'],5,10)

Wordpress after checking username and password how log in

hi i created this code below in my wordpress theme within my login.php page i created conditional statements successfully without any problem but in my last if statement when the username and password is correct i can't when this statement is correct i log in?
i want when the username and password is correct directly show legge in username and add the log out link to log out from the theme.
<?php
$error = '';
$success = '';
global $user_identity;
if(isset($_POST['task']) && $_POST['task'] == 'login') {
$username = esc_attr($_POST['login_username']);
$password = esc_attr($_POST['login_password']);
$remember = esc_attr($_POST['login_remember']);
$user = get_user_by('login', $username);
$user_id = $user->ID;
$user_data = get_userdata($user_id);
$user_login = $user_data->user_login;
$user_pass = $user_data->user_pass;
if($username == '' && $password == '') {
$error = 'Please Fill Required Fields!';
}
if($username == '') {
$error = 'Please Enter Your Username';
}
if($password == '') {
$error = 'Please Enter Your Password';
}
if($user_login != $username) {
$error = 'The Username is Incorrect';
}
if($user_pass != $password) {
$error = 'The Password is Incorrect';
}
if($user_login == $username && $user_pass == $password) {
}
}
?>
hey just create array of user data and passed into wp_signon($data,false) see below.
$login_data = array();
$login_data['user_login'] = $username;
$login_data['user_password'] = $password;
$login_data['remember'] = $remember; // set true or false for remember
$user_verify = wp_signon( $login_data, false );
if ( is_wp_error($user_verify) )
{
echo $user->get_error_message();
exit;
} else {
header("Location: " . home_url() . "/login/error/");
}
read document for more detail wp_signon()

Categories