Validation for registration page in PHP - php

I have a registration page and I want to validate it. I have this code:
$msg = "";
$msg_3 = "";
if(isset($_POST['submit'])) {
$First_Name = ((isset($_POST['First_Name']))?sanitize($_POST['First_Name']):'');
$Last_Name = ((isset($_POST['Last_Name']))?sanitize($_POST['Last_Name']):'');
$email = ((isset($_POST['email']))?sanitize($_POST['email']):'');
$confirm_email = ((isset($_POST['confirm_email']))?sanitize($_POST['confirm_email']):'');
$mobile_number = ((isset($_POST['mobile_number']))?sanitize($_POST['mobile_number']):'');
$password = ((isset($_POST['password']))?sanitize($_POST['password']):'');
$confirm_password = ((isset($_POST['confirm_password']))?sanitize($_POST['confirm_password']):'');
$gender = ((isset($_POST['gender']))?sanitize($_POST['gender']):'');
$day = ((isset($_POST['day']))?sanitize($_POST['day']):'');
$month = ((isset($_POST['month']))?sanitize($_POST['month']):'');
$year = ((isset($_POST['year']))?sanitize($_POST['year']):'');
$insurance = ((isset($_POST['insurance']))?sanitize($_POST['insurance']):'');
$agree = ((isset($_POST['agree']))?sanitize($_POST['agree']):'');
$sql = "SELECT email, mobile_number FROM customers WHERE email ='$email' OR mobile_number ='$mobile_number'";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
if ($email == $row['email']) {
$msg = "<span class='text-danger'>The email address you've entered is already associated with another account.
<br>Please sign in or enter a different email address. Please try again.</span>";
} if ($mobile_number == $row['mobile_number']) {
$msg_3 = "<span class='text-danger'>The mobile phone number you've entered is already associated with another account.
<br>Please sign in or enter a different number. Please try <br>again.</span>";
}
}
} else {
// Insert into database and send email
}
Now how could I validate each field if it is empty and print different messages under each field in this nested if and while. I'm getting confused.

If you will use same names in db as in form you could use something like this:
$keys = ['gender', 'email', 'mobile_number']; //etc
$errors = [];
while ($row = $result->fetch_assoc()) {
array_walk($keys, function ($key) {
if (empty($row[$key])) {
$errors[] = "$key is required"
}
if (isset($_POST[$key]) && $_POST[$key] == $row[$key]) {
$errors[] = "please enter $key"
}
})
}
if you need to have more customized messages you might map keys to error text like:
$keys = ['gender' => ['equal' => 'your error message', 'empty' => 'empty msg'], 'email' => ['equal' => 'email validation error', 'empty' => 'error msg 2']]; //etc
$errors = [];
while ($row = $result->fetch_assoc()) {
array_walk($keys, function ($errorMsg, $key) {
if (isset($_POST[$key]) && $_POST[$key] == $row[$key]) {
$errors[$key] = $errorMsg['equal'];
}
if (empty($row[$key])) {
$errors[$key] = $errorMsq['empty'];
}
})
}

Do not repeat
Prevent SQL Injection
You can do something like this.
<?php
if(isset($_POST['submit'])) {
$errors = [];
function getPost($postIndex, $errorMessage = '') {
global $errors;
if (!empty( $_POST[$postIndex] )) {
$value = $_POST[$postIndex];
return $value;;
} else {
$errors[$postIndex] = $errorMessage;
return null;
}
}
function validateString($s) {
return htmlspecialchars(trim($s));
}
getPost('First_Name', 'Firstname Cannot Be Empty');
getPost('Last_Name', 'Lastname cannot be empty');
$email = getPost('email', 'Your Error Message');
getPost('confirm_email', 'Your Error Message');
$mobile_number = getPost('mobile_number', 'Your Error Message');
getPost('password', 'Your Error Message');
getPost('confirm_password', 'Your Error Message');
getPost('gender', 'Your Error Message');
getPost('day', 'Your Error Message');
getPost('month', 'Your Error Message');
getPost('year', 'Your Error Message');
getPost('insurance', 'Your Error Message');
getPost('agree', 'Your Error Message');
$stmt = $mysqli -> prepare('SELECT email, mobile_number FROM customers WHERE email =? OR mobile_number =?');
if (
$stmt &&
$stmt -> bind_param('ss', $email, $mobile_number) &&
$stmt -> execute() &&
$stmt -> store_result() &&
$stmt -> bind_result($dbEmail, $dbMobileNumber) &&
$stmt -> fetch()
) {
if ($email == $dbEmail) {
// email equal error message
} if ($mobile_number == $row['mobile_number']) {
// mobile number equal error message
}
}
if (count($errors)) {
echo "You have an error";
}
// or get the post index in your HTML form and show the error message there
// <?php isset($errors['firstName']) ? echo $errors['firstname'] : null;
}

Related

faulty error output in my registration form

I am trying to make a registration form and doing some checks before running SQL queries, but as i test and try to generate multiple errors, i am getting only the error that comes first, or sometimes no error at all. I am unable to locate where i have made error.
The following is the code in PHP.
//function to filter only phone numbers
function get_phone($number) {
return preg_replace('#[^0-9]#', '', $number);
}
//function to take only alphabets.
function get_alpha($alphabets){
return preg_replace('#[^a-z]#', '', $alphabets);
}
//function to check email.
function isValidEmail($email){
if (strlen ($email) > 50){
$errors[] = 'email address too long, please use a shorter email address..!';
} else {
return (filter_var($email, FILTER_VALIDATE_EMAIL));
}
}
function output_errors($errors){
$output = array();
foreach($errors as $error) {
$output[] = '<li>' . $error . '</li>';
}
return '<ul>' . implode('', $output) . '</ul>';
}
if (empty($_POST) === false) {
//store the text box field names of the form to local variables.
$cust_name = $_POST['name1'];
$cust_email = $_POST['email'];
$cust_phone = $_POST['phone'];
$cust_addr1 = $_POST['addr1'];
$cust_addr2 = $_POST['addr2'];
$cust_city = $_POST['city'];
$cust_state = $_POST['state'];
$cust_country = $_POST['country'];
$username = $_POST['uname'];
$password = $_POST['passwd'];
$cnf_passwd = $_POST['cnf_passwd'];
$sec_que = $_POST['sec_que'];
$sec_ans = $_POST['sec_ans'];
//sanitize the inputs from the users end.
$cust_name = sanitize($username);
$cust_phone = get_phone($cust_phone);
$cust_addr1 = sanitize($cust_addr1);
$cust_addr2 = sanitize($cust_addr2);
$cust_city = get_alpha($cust_city);
$cust_state = get_alpha($cust_state);
$cust_country = get_alpha($cust_country);
$username = sanitize($username);
$password = md5($password);
$cnf_passwd = md5($cnf_passwd);
$sec_que = sanitize($sec_que); //put up dropdown menu
$sec_ans = sanitize($sec_ans);
$cust_email = isValidEmail($cust_email);
//check for error handling in form data
//1. check for empty fields,
if ($cust_name == "" || $cust_phone == "" ||
$cust_addr1 == "" || $username == "" ||
$password == "" || $cnf_passwd == "" ||
$sec_que == "" || $sec_ans == ""
) {
$errors[] = 'No blank fields allowed, please fill out all the required fields..!';
//2.check for field lengths
} else if (strlen($cust_name) < 3 || strlen($cust_name > 20)) {
$errors[] = 'The name length should be between 3 to 20, please check & correct..!';
//3. check for phone number length
} else if (strlen($cust_phone) < 10 || strlen($cust_phone) > 11) {
$errors[] = 'The phone number must be 10 or 11 digits..!';
//4. check for address input lengths.
} else if (strlen($cust_addr1) < 5 || strlen($cust_addr1) > 50) {
$errors[] = 'Please provide a valid address..to serve you better..!';
//5. check if the password fields content match.
//length is not checked because the entered values will be converted to MD5 hash
// of 32 characters.
} else if ($password != $cnf_passwd) {
$errors[] = 'The passwords do not match. Please enter your passwords again..!';
// 6. check for length of the security answers.
} else if (strlen($sec_ans) < 5 || strlen($sec_ans) > 50) {
$errors[] = 'Please enter a proper security answer..!';
} //7. check for valid email address
else if($cust_email == false){
$errors[] = 'The email address you entered is not valid, please check and correct..!';
} else {
execute the SQL queries and enter the values in the database.
echo 'GOOD...TILL NOW..!!!';
}
} else {
$errors [] = 'No data received, Please try again..!!';
}
if(empty($errors) === false) {
?>
<h2>The Following errors were encountered:</h2>
<?php
echo output_errors($errors); //output the errors in an ordered way.
}
?>
When you use this structure:
if () {
} else if () {
} else if () {
}
// etc.
then only one condition can be satisfied. As soon as one of those if conditions is true, the rest of the else if blocks and the final else block are ignored.
If your conditions aren't mutually exclusive, put them in their own separate blocks:
if () {
}
if () {
}
if () {
}
// etc.

Codeigniter - Update email only if the email doesn't exist in the database

I have an update page for my users where they can edit their name, email and other info.
So far, they can edit everything. Including their email. They can enter an email that already exists in the database without any issue.
I have tried adding this form validation rule
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|is_unique[users.email]');
But that doesn't help because it will ask the user to enter another email if they click the save button, even if they don't want to change their email.
I just want to make it so that when they click the save button, only update the email if the user has changed it AND check that the email doesn't exist in the database before saving.
I have tried doing this but no luck.
The code that I'm playing with:
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$email = $this->input->post('email');
$uid = $this->session->userdata('uid');
//$query = $this->db->get('dayone_entries');
$query = $this->db->query('SELECT uid, email FROM users');
$sql = "UPDATE users SET first_name = '{$first_name}', last_name = '{$last_name}', email = '{$email}' WHERE uid = $uid LIMIT 1";
$this->db->query($sql);
if ($this->db->affected_rows() === 1) {
return true;
} else {
return false;
}
You can try the following code :
$this->form_validation->set_rules('email', 'lang:email', 'trim|required|valid_email|callback__is_unique_email[email]');
and the callback function should look like this :
public function _is_unique_email($value, $field){
$result = $this->db->where('uid !=', $this->session->userdata('uid'))
->where($field, $value)
->get('users')
->row_array();
if ($result) {
$this->form_validation->set_message('_is_unique_email', $this->lang->line('_is_unique_'));
return false;
}
return true;
}
Your Javascript file:
$("#form_id").validate({
rules: {
email: {
required: true,
email: true,
remote: {
type: "post",
url: "pathtocontroller/controller.php/checkEmail",
}
}
},
messages: {
email: {
required: "Please enter Email!",
email: "Please enter valid Email!",
remote: "Email already not available!"
}
}
Your Controller File:
function checkEmail() {
$userArr = $this->input->post();
$id = $this->session->userdata('id');//if you have stored id within session else pass it within remote function
if (isset($userArr["email"])) {
if ($id != '') {
$ext_cond = "id !='" . $id . "'";
}
echo $this->your_model_name->getUserValidation('your_email_field_name', $userArr['email'], $ext_cond);
exit;
}
exit;
}
Your Model:
public function getUserValidation($usertype = '', $value = '', $cond = '') {
if ($usertype != '' && $value != '') {
$this->db->select($usertype);
$this->db->from($this->main_table);
if ($cond != '') {
$this->db->where($cond);
}
if (is_array($usertype)) {
foreach ($usertype as $key => $type_value) {
$this->db->where($type_value, $value[$key]);
}
} else {
$this->db->where($usertype, $value);
}
$user_data = $this->db->get()->result_array();
// echo $this->db->last_query();exit;
if (is_array($user_data) && count($user_data) > 0) {
return "false";
} else {
return "true";
}
} else {
return "false";
}
}
use validate library : http://docs.jquery.com/Plugins/Validation/Methods/remote
your javascript :
$("#yourFormId").validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "checkmail.php",
type: "post"
}
}
},
messages: {
email: {
required: "Please Enter Email!",
email: "This is not a valid email!",
remote: "Email already in use!"
}
}
});
checkmail.php:
<?php
$registeredEmails = array('test1#test.com', 'test2#test.com', 'test3#test.com');
$requestedEmail = $_POST['email'];
if( in_array($requestedEmail, $registeredEmails) ){
echo 'false';
}
else{
echo 'true';
}
?>
if you use codeigniter means use checkmail.php as a controller function..
you can pass your $registeredEmails array values as $registeredEmails[] = "your query result which is in for loop".

PHP PDO not inserting or throwing error

The email is not being inserted into the database, however I am receiving an echo of success without any errors. I'm not sure what is going wrong. I've tried it with a duplicate email and I get the duplicate email message so it is connecting to the database, and it will not insert when it is a duplicate; however, it seems to not be inserting anything when it is not a duplicate. It seems to just skip the step of uploading.
<?php
include 'db_functions.php';
$_POST['email'] = 'somenewemail#gmail.com';
if(isset($_POST['email']) && ($_POST['email'] != NULL || $_POST['email'] != '')){
$ERRORS = array();
$cleanEmail = htmlentities($_POST['email']);
$database = dbconnlocal();
$queryEmailExists = $database->prepare("SELECT email FROM email_list WHERE email= ?");
$queryUploadEmail = $database->prepare("INSERT INTO email_list (email) VALUES ( ? )");
$database->beginTransaction();
try
{
$queryEmailExists->execute(array($cleanEmail));
$results = $queryEmailExists->fetchAll(PDO::FETCH_ASSOC);
$dbEmail = $results[0]['email'];
if(trim($dbEmail) == trim($cleanEmail)) {
// duplicate email
throw new Exception('duplicateEmail');
} else {
// new email
$queryUploadEmail->execute(array($cleanEmail));
echo json_encode('success');
}
}
catch (Exception $e)
{
switch(trim($e->getMessage())) {
case 'duplicateEmail':
// handle duplicate error
$ERRORS['error'] = 'duplicateEmail';
break;
default:
// handle default errors
$ERRORS['error'] = 'default';
break;
}
echo json_encode($ERRORS['error']);
}
} else { echo json_encode('emptyEmail'); /* empty email */ };
?>

Looping correctly though array

Okay so I'm looping through the results that contains two question IDs and two answers and I'm trying to match the two answers with the two answers from the form submission.
I'm not sure what I'm doing wrong.
<?php
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
//Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = false;
if (trim($_POST['answer1']) == '') { $errors = true; }
if (trim($_POST['answer2']) == '') { $errors = true; }
// Error checking, make sure all form fields have input
if ($errors) {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => $errors, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc,$_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc,$_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc,$_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc,$_POST['question1']);
$question2 = mysqli_real_escape_string($dbc,$_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc,$query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if (($answer == $answer1Post) && ($answer == $answer2Post)) {
} else {
$errors = true;
$message = "Your answers did not match the answers inside the database!";
$output = array('errorsExist' => $errors, 'message' => $message);
}
}
} else {
$errors = true;
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => $true, 'message' => $message);
}
}
}
//Output the result
$output = json_encode($output);
echo $output;
?>
Since your question is not clear in the first place, so I'm assuming that the question you are asking is "why you're not getting any matching results, when you've the correct answers in the database?". Please correct me, if this is wrong.
The logic can be like this:-
<?php
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
// Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = false;
if (trim($_POST['answer1']) == '') { $errors = true; }
if (trim($_POST['answer2']) == '') { $errors = true; }
// Error checking, make sure all form fields have input
if ($errors) {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => $errors, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc, $_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc, $_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc, $_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc, $_POST['question1']);
$question2 = mysqli_real_escape_string($dbc, $_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc, $query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if ($answer == $answer1Post) {
// The first answer is correct
$errors = false;
$message = "Your first answer is correct!";
} else if ($answer == $answer2Post) {
// The second answer is correct
$errors = false;
$message = "Your second answer is correct!";
} else {
$errors = true;
$message = "Your answers did not match the answers inside the
}
$output = array('errorsExist' => $errors, 'message' => $message);
}
} else {
$errors = true;
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => $true, 'message' => $message);
}
}
}
// Output the result
$output = json_encode($output);
echo $output;
?>
It's better to have more segregation of logical conditions. In this case, it's your two answers to check for.
Hope it helps.

not returning sufficient rows

What I'm trying to figure out here is how to access the different array values that I need. I have the following query and it returns this for an array when the print_r() is applied. For some reason it only does the first row from the db table. It should return a whole another row.
<?php
session_start();
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
//Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = "no";
if((empty($_POST['answer1'])) || (trim($_POST['answer1'])=="") || ($_POST['answer1'] == NULL) || (!isset($_POST['answer1']))){$errors = "yes";}
if((empty($_POST['answer2'])) || (trim($_POST['answer2'])=="") || ($_POST['answer2'] == NULL) || (!isset($_POST['answer2']))){$errors = "yes";}
// Error checking, make sure all form fields have input
if ($errors == "yes") {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => true, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc,$_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc,$_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc,$_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc,$_POST['question1']);
$question2 = mysqli_real_escape_string($dbc,$_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc,$query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if ($answer == $answerPost) {
} else {
$errors = "yes";
$message = "Your answers did not match the answers inside the database!";
$output = array('errorsExist' => true, 'message' => $message);
}
}
} else {
$errors = "yes";
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => true, 'message' => $message);
}
}
}
//Output the result
$output = json_encode($output);
echo $output;
?>
Because you just fetch the first one, where you should loop on the result set instead:
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '$userID'";
$result = mysqli_query($dbc,$query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
print_r($row);
}
}
By the way, you should be using prepared statements to avoid SQL injection.
You need to wrap your fetch in a loop. e.g.
if (mysqli_num_rows($result) > 0)
{
while (($row = mysqli_fetch_array($result)) !== false)
{
if ($row['answer'] == $answerPost)
{
// $row matches what we're looking for
}
else
{
$errors = "yes";
$message = "Your answers did not match the answers inside the database!";
$output = array('errorsExist' => true, 'message' => $message);
}
print_r($row);
}
}

Categories