To display invalid email and password error message - php

In view: login.php
I am using this view file in two places one for user login and other displaying the invalid user and password message. Below i mentioned some code but it does not work. give me any suggestion regarding this problem.
<div class="login-content">
/*
message to be displayed here:
i try this one:<?php if(!(authentication($email,$password) == TRUE)){
echo "Invalid email address or password";
}?>
*/
<form action="<?php echo site_url('auth/check');?>" method="POST" class="margin-bottom-0" data-parsley-validate="true" onsubmit = "return Validate();" >
<div class="form-group m-b-15">
<input type="text" name="txtemail" id="txtemail" class="form-control input-lg" placeholder="<?php echo $language['Email'];?>" data-parsley-required='true' maxlength="95"/>
</div>
<div class="form-group m-b-15">
<input type="password" name="txtpassword" id="txtpassword" class="form-control input-lg" placeholder="<?php echo $language['Password'];?>" data-parsley-required='true' maxlength="95"/>
</div>
In Controller: Auth.php
This is a function for checking the user validation. I want to display a message using this function in else condition.
public function check(){
$email = $this->input->post('txtemail');
$password = $this->encrypt($this->input->post('txtpassword'));
$this->load->model('cmsuser_model');
$user = $this->cmsuser_model->authentication($email,$password);
if(!is_null($user))
{
$this->session->set_userdata('user', $user);
$this->session->set_userdata('profile_image',$user->image);
$this->session->set_userdata('is_manager','0');
$this->load->model('association_model');
$table = '';
$limit = '';
$order_by = '';
$group_by = '';
$start = '';
$fields = '';
$where = array();
$where['created_by'] = $this->session->userdata['user']->cmsuid;
$dt = $this->association_model->get_all($fields, $where, $table, $limit, $order_by, $group_by, $start);
$this->session->set_userdata('ass_id', $dt[0]['ass_id']);
redirect(base_url('index.php/welcome'), 'refresh');
}
else{
//Browser redirect to this else condition but i am not able to display message in `view(login.php)` file.
redirect(base_url('index.php/auth/login'), 'refresh');
}
exit;
}

public function check(){
$email = $this->input->post('txtemail');
$password = $this->encrypt($this->input->post('txtpassword'));
$this->load->model('cmsuser_model');
$user = $this->cmsuser_model->authentication($email,$password);
if(!is_null($user))
{
$this->session->set_userdata('user', $user);
$this->session->set_userdata('profile_image',$user->image);
$this->session->set_userdata('is_manager','0');
$this->load->model('association_model');
$table = '';
$limit = '';
$order_by = '';
$group_by = '';
$start = '';
$fields = '';
$where = array();
$where['created_by'] = $this->session->userdata['user']->cmsuid;
$dt = $this->association_model->get_all($fields, $where, $table, $limit, $order_by, $group_by, $start);
$this->session->set_userdata('ass_id', $dt[0]['ass_id']);
redirect(base_url('index.php/welcome'), 'refresh');
}
else{
$url=echo base_url('login.php').'?status=err';
redirect($url, 'refresh');
//this will redirect you to the login page with the parameter status in the url
}
exit;
}
in login.php View File
<?php
$satatus = $_GET['status'];
if($status == 'err'){
?>
//add this div right above the login section
<div>Wrong Username/Password !!</div>
<div class="login-content">
/*
message to be displayed here:
i try this one:<?php if(!(authentication($email,$password) == TRUE)){
echo "Invalid email address or password";
}?>
*/
<form action="<?php echo site_url('auth/check');?>" method="POST" class="margin-bottom-0" data-parsley-validate="true" onsubmit = "return Validate();" >
<div class="form-group m-b-15">
<input type="text" name="txtemail" id="txtemail" class="form-control input-lg" placeholder="<?php echo $language['Email'];?>" data-parsley-required='true' maxlength="95"/>
</div>
<div class="form-group m-b-15">
<input type="password" name="txtpassword" id="txtpassword" class="form-control input-lg" placeholder="<?php echo $language['Password'];?>" data-parsley-required='true' maxlength="95"/>
</div>
<?php
}
?>

Related

How Can I show array content inside the body of html

This is my custom user registration form WordPress site, actually, this is my first custom development, and here all the data passes the DB my problem is I need to show my error message inside the HTML code. how can I do it? can anyone help me to solve this problem? now my error messages show like this (Array ( [username_empty] => Needed Username [email_valid] => Email has no valid value [texnumber_empty] => Needed Tax Number )) but I need only show error message only Ex: this one ( [username_empty] => Needed Username) I need to show "Needed Username"
Like this.
if (is_user_logged_in()) {
// echo '<script>alert("Welcome, registered user!")</script>';
echo '<script type="text/javascript">';
echo 'alert("Welcome, registered user!");';
echo 'window.location.href = "Url";';
echo '</script>';
} else {
// echo 'Welcome, visitor!';
global $wpdb;
if ($_POST) {
$username = $wpdb->escape($_POST['user_login']);
$email = $wpdb->escape($_POST['user_email']);
$taxnumber = $wpdb->escape($_POST['tax_number']);
$password = $wpdb->escape($_POST['user_pass']);
$ConfPassword = $wpdb->escape($_POST['user_confirm_password']);
$error = array();
if (strpos($username, ' ') !== FALSE) {
$error['username_space'] = "Username has Space";
}
if (empty($username)) {
$error['username_empty'] = "Needed Username";
}
if (username_exists($username)) {
$error['username_exists'] = "Username already exists";
}
if (!is_email($email)) {
$error['email_valid'] = "Email has no valid value";
}
if (email_exists($email)) {
$error['email_existence'] = "Email already exists";
}
if (empty($taxnumber)) {
$error['texnumber_empty'] = "Needed Tax Number";
}
if (strcmp($password, $ConfPassword) !== 0) {
$error['password'] = "Password didn't match";
}
if (count($error) == 0) {
$user_id = wp_create_user($username, $password, $email);
$userinfo = array(
'ID' => $user_id,
'user_login' => $username,
'user_email' => $email,
'user_pass' => $password,
'role' => 'customer',
);
// Update the WordPress User object with first and last name.
wp_update_user($userinfo);
// Add the company as user metadata
update_user_meta($user_id, 'tax_number', $taxnumber);
echo '<script type="text/javascript">';
echo 'alert("User Created Successfully");';
echo 'window.location.href = "url";';
echo '</script>';
exit();
} else {
print_r($error);
}
}
?>
<section id="wholesale-custom-register-form">
<div class="container wholesale-custom-register-form">
<div class="register-form">
<div class="register-form-title">
<h1>Wholesale Register Form</h1>
</div>
<div class="wholesale-register">
<form class="register-fm" method="POST">
<div class="form-group">
<label>User Name</label>
<input class="form-control" type="text" name="user_login" id="user_login" placeholder="Username" />
<?php foreach ($error as $error) {
echo $error . "<br>";
} ?>
</div>
<div class="form-group">
<label>Email</label>
<input class="form-control" type="email" name="user_email" id="user_email" placeholder="Email" />
</div>
<div class="form-group">
<label>Tax Number</label>
<input class="form-control" type="text" name="tax_number" id="tax_number" placeholder="Tax Number" />
</div>
<div class="form-group">
<label>Enter Password</label>
<input class="form-control" type="password" name="user_pass" id="user_pass" placeholder="Password" />
</div>
<div class="form-group">
<label>Enter Cofirm Password</label>
<input class="form-control" type="password" name="user_confirm_password" id="user_confirm_password" placeholder="Cofirm Password" />
</div>
<div class="form-group">
<button class="custom-register-btn" type="submit" name="btnsubmit">Log In</button>
</div>
</form>
</div>
</div>
</div>
</section>
<?php
};
This is my code I will try many times but I can't get the error messages inside the HTML body.
You want to make an AJAX call to register a user then use a callback function to check for success. If a field is invalid you also check it with javascript.
So you would need to refactor your code, seperate it into frontend/backend code and connect it via AJAX.
Write your PHP code as "add_action_hook" and register function
Onclick validate fields and inputs
Call the hook via AJAX (url: "/wp-admin/admin-ajax.php")
Return result
These are just very abstract steps, you'll need to gather some intel for yourself. You could take a look at this: https://awhitepixel.com/blog/wordpress-use-ajax/ and https://docs.wpvip.com/technical-references/security/validating-sanitizing-and-escaping/
I would do something like this
if (is_user_logged_in()) {
// echo '<script>alert("Welcome, registered user!")</script>';
echo '<script type="text/javascript">';
echo 'alert("Welcome, registered user!");';
echo 'window.location.href = "Url";';
echo '</script>';
} else {
// echo 'Welcome, visitor!';
global $wpdb;
if ($_POST) {
$username = $wpdb->escape($_POST['user_login']);
$email = $wpdb->escape($_POST['user_email']);
$taxnumber = $wpdb->escape($_POST['tax_number']);
$password = $wpdb->escape($_POST['user_pass']);
$ConfPassword = $wpdb->escape($_POST['user_confirm_password']);
if (strpos($username, ' ') !== FALSE) {
$errorMsg[] = "Username has Space";
}
if (empty($username)) {
$errorMsg[] = "Needed Username";
}
if (username_exists($username)) {
$errorMsg[] = "Username already exists";
}
if (!is_email($email)) {
$errorMsg[] = "Email has no valid value";
}
if (email_exists($email)) {
$errorMsg[] = "Email already exists";
}
if (empty($taxnumber)) {
$errorMsg[] = "Needed Tax Number";
}
if (strcmp($password, $ConfPassword) !== 0) {
$errorMsg[] = "Password didn't match";
}
if (count($errorMsg) == 0) {
$user_id = wp_create_user($username, $password, $email);
$userinfo = array(
'ID' => $user_id,
'user_login' => $username,
'user_email' => $email,
'user_pass' => $password,
'role' => 'customer',
);
// Update the WordPress User object with first and last name.
wp_update_user($userinfo);
// Add the company as user metadata
update_user_meta($user_id, 'tax_number', $taxnumber);
echo '<script type="text/javascript">';
echo 'alert("User Created Successfully");';
echo 'window.location.href = "url";';
echo '</script>';
exit();
} else {
print_r($errorMsg);
}
}
?>
<section id="wholesale-custom-register-form">
<div class="container wholesale-custom-register-form">
<div class="register-form">
<div class="register-form-title">
<h1>Wholesale Register Form</h1>
</div>
<div class="wholesale-register">
<form class="register-fm" method="POST">
<div class="form-group">
<label>User Name</label>
<input class="form-control" type="text" name="user_login" id="user_login" placeholder="Username" />
<?php foreach ($errorMsg as $error) {
?>
<div>
<strong><?= $error; ?> </strong>
</div>
<?php
} ?>
</div>
<div class="form-group">
<label>Email</label>
<input class="form-control" type="email" name="user_email" id="user_email" placeholder="Email" />
</div>
<div class="form-group">
<label>Tax Number</label>
<input class="form-control" type="text" name="tax_number" id="tax_number" placeholder="Tax Number" />
</div>
<div class="form-group">
<label>Enter Password</label>
<input class="form-control" type="password" name="user_pass" id="user_pass" placeholder="Password" />
</div>
<div class="form-group">
<label>Enter Cofirm Password</label>
<input class="form-control" type="password" name="user_confirm_password" id="user_confirm_password" placeholder="Cofirm Password" />
</div>
<div class="form-group">
<button class="custom-register-btn" type="submit" name="btnsubmit">Log In</button>
</div>
</form>
</div>
</div>
</div>
</section>
<?php
};

Error message not shown when trying to login to an invalid username

When I tried logging in to an invalid username, I got no error message. Instead it redirected to the same login page.
Here is the controller:
function cekuser()
{
$username = strip_tags(stripslashes($this->input->post('username', TRUE)));
$password = strip_tags(stripslashes($this->input->post('password', TRUE)));
$u = $username;
$p = md5($password);
$cadmin = $this->Auth_model->check_login($u, $p);
if (!$cadmin) {
redirect('administrator/gagallogin');
} else {
if ($cadmin['level'] == '1') {
$this->session->set_userdata('masuk', true);
$this->session->set_userdata('user', $u);
$this->session->set_userdata('akses', '1');
$idadmin = $cadmin['id'];
$user_nama = $cadmin['nama'];
$this->session->set_userdata('idadmin', $idadmin);
$this->session->set_userdata('nama', $user_nama);
}
}
if ($this->session->userdata('masuk') == true) {
redirect('administrator/berhasillogin');
} else {
redirect('administrator/gagallogin');
}
}
function berhasillogin()
{
redirect('dashboard');
}
function gagallogin()
{
$url = base_url('administrator');
echo $this->session->set_flashdata('msg', 'Username Atau Password Salah');
redirect($url);
}
and here is for the login views:
<form class="form-signin" action="<?php echo base_url() . 'administrator/cekuser' ?>" method="post">
<label for="inputEmail" class="sr-only">NIP</label>
<input class="form-control" type="text" name="username" placeholder="Username" required>
<br />
<label for="inputPassword" class="sr-only">Password</label>
<input class="form-control" type="password" name="password" placeholder="Password" style="margin-bottom:1px;" required>
<br />
<br />
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
</form>
Is there any solution? Thank you.
You don't echo the flash data, you just set it.
function gagallogin()
{
$url = base_url('administrator');
$this->session->set_flashdata('msg', 'Username Atau Password Salah');
redirect($url);
}
In the form, you set the flash message with PHP. Change your form to a PHP file and do something like this:
<?php if ($this->session->flashdata('msg') { ?>
<p class="text-danger">Error: <?php echo $this->session->flashdata('msg'); ?></p>
<?php } ?>
<form class="form-signin" action="<?php echo base_url() . 'administrator/cekuser' ?>" method="post">

Cannot display alert once the user login inputs incorrect credentials PHP PDO

index.php
This is the login form
<div class="modal-body">
<form action="loginPDO.php" method="post">
<?php if(isset($message))
{
echo '<label class="text-danger">'.$message.'</label>';
} ?>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Username:</label>
<input type="text" name="username" id="username" placeholder="Enter Username" class="form-control">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Password:</label>
<input type="password" name="password" id="password" placeholder="Enter Password" class="form-control">
</div>
<div class="form-group">
<button type="submit" name="login" id="login" class="btn btn-primary">Login</button>
<button type="button" class="btn btn-info">Register</button>
</div>
</form>
</div>
loginPDO.php
<?php
include 'dbconnection.php';
if(isset($_POST["login"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$message = '<label>All fields are required</label>';
header("location:index.php");
}
else
{
$query = "SELECT * FROM users WHERE username = :username AND password = :password";
$statement = $conn->prepare($query);
$statement->execute(
array(
'username' => $_POST["username"],
'password' => $_POST["password"]
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["username"] = $_POST["username"];
header("location:dashboard.php");
}
else
{
$message = '<label>Wrong Data</label>';
header("location:index.php");
}
}
}
?>
Hi Guys, I want to know how to display the alert message once the user inputs incorrect credentials
For example, Imagine the user inputs wrong credentials once the user clicks the login button it automatically appears the alert message above Username.
$message just exists in file loginPDO.php and ...
$message = '<label>Wrong Data</label>';
header("location:index.php");
Is not sufficient to pass the $message variable to index.php.
As said in comments you can try
// file loginPDO.php
$message = '<label>Wrong Data</label>';
header("location:index.php?error=" . urlencode("Wrong Data"));
// file index.php
<?php
$message = isset($_GET['error']) ? $_GET['error'] : null; // get the error from the url
if(!empty($message)) {
echo '<label class="text-danger">'.$message.'</label>';
} ?>

Account Edit in CodeIgniter

I tried to edit users account but when I loaded the view it does not display the users default account information.Below is my model view and controller. Any help would be greatly appreciated.
I have a database which includes includes all the users information. so I want to retrieve it and perform an update function.
CONTROLLER
/**
* This function is used load user edit information
* #param number $userId : Optional : This is user id
*/
function editOld($userId = NULL)
{
if($userId == null)
{
redirect('pages/settings');
}
$data['userInfo'] = $this->settings_model->getUserInfo($userId);
$data['title'] = 'Settings';
$this->load->view('templates/header');
$this->load->view('pages/settings', $data);
$this->load->view('templates/footer');
}
/**
* This function is used to edit the user information
*/
function editUser()
{
$this->load->library('form_validation');
$userId = $this->session->userdata('user_id');
$this->form_validation->set_rules('name','Full Name','trim|required|max_length[128]|xss_clean');
$this->form_validation->set_rules('email','Email','trim|required|valid_email|xss_clean|max_length[128]');
$this->form_validation->set_rules('username','Username','trim|required|xss_clean|min_length[3]');
$this->form_validation->set_rules('birthday','Birthday','required|xss_clean');
$this->form_validation->set_rules('gender','Gender','required|xss_clean');
$this->form_validation->set_rules('mobile','Mobile Number','required|min_length[9]|xss_clean');
if($this->form_validation->run() == FALSE)
{
$this->editOld($userId);
}
else
{
$name = $this->input->post('name');
$username = $this->input->post('username');
$email = $this->input->post('email');
$bio = $this->input->post('bio');
$mobile = $this->input->post('mobile');
$birthday = $this->input->post('birthday');
$gender = $this->input->post('gender');
$userInfo = array();
if(empty($password))
{
$userInfo = array('email'=>$email, 'username'=>$username, 'name'=>$name,
'mobile'=>$mobile, 'bio'=>$bio, 'birthday'=>$birthday, 'gender'=>$gender, 'updatedBy'=>$userId, 'updatedDtm'=>date('Y-m-d H:i:s'));
}
else
{
$userInfo = array('email'=>$email, 'username'=>$username, 'name'=>$name,
'mobile'=>$mobile, 'bio'=>$bio, 'birthday'=>$birthday, 'gender'=>$gender, 'updatedBy'=>$userId, 'updatedDtm'=>date('Y-m-d H:i:s'));
}
$result = $this->settings_model->editUser($userInfo, $userId);
if($result == true)
{
$this->session->set_flashdata('success', 'Profile updated successfully');
}
else
{
$this->session->set_flashdata('error', 'Profile update failed');
}
redirect('pages/settings');
}
}
MODEL
function getUserInfo($userId)
{
$this->db->select('id, name, email, username, mobile, birthday, gender, bio');
$this->db->from('users');
$this->db->where('isDeleted', 0);
$this->db->where('id', $userId);
$query = $this->db->get();
return $query->result();
}
/**
* This function is used to update the user information
* #param array $userInfo : This is users updated information
* #param number $userId : This is user id
*/
function editUser($userInfo, $userId)
{
$this->db->where('id', $userId);
$this->db->update('users', $userInfo);
return TRUE;
}
VIEW
<?php
$userId = '';
$name = '';
$email = '';
$mobile = '';
$username = '';
$birthday = '';
$bio = '';
if(!empty($userInfo))
{
foreach ($userInfo as $uf)
{
$userId = $uf->id;
$name = $uf->name;
$email = $uf->email;
$mobile = $uf->mobile;
$username = $uf->username;
$birthday = $uf->birthday;
$bio = $uf->bio;
}
}
?>
<form class="col s12" role="form" action="<?php echo base_url() ?>settings/editUser" method="post" id="editUseri" role="form">
<div class="row">
<div class="input-field col s12">
<input id="name" type="text" class="validate" name="name" value="<?php echo $name; ?>">
<input type="hidden" value="<?php echo $userId; ?>" name="userId" id="userId" />
<label for="name">Full Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="username" type="text" class="validate" data-length="15" name="username" value="<?php echo $username; ?>">
<label for="username">Username</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="email" type="text" class="validate" name="email" value="<?php echo $email; ?>">
<label for="email">Email</label>
</div>
</div>
<div class="box-footer">
<input type="submit" class="btn btn-primary" value="Submit" />
<input type="reset" class="btn btn-default" value="Reset" />
</div>
</form>
You can just pass your details into session and use sessions to display it. remember to update the session .
value="<?php echo $this->session->userdata('username'); ?>"
mark as correct if it works for you.
Try to add :
$this->db->last_query()
to check what is the query going. I think it would needs to set the
$query->result();
$this->db->set() the data part for handling update query
try this only for debug your error
you not checked user session set or not
change from
if($this->form_validation->run() == FALSE)
{
$this->editOld($userId);
}else{
....
....
}
to
if($this->form_validation->run() == FALSE)
{
//your validation error
echo "validation error";
}else if($userId){
//if session set for user
$this->editOld($userId);
}else{
....
....
}

Misbehaving Login Script

I have this PHP login script that SHOULD be taking the entered username & password, checking it against a value in MySQL (with the password encrypted via SHA1) and then redirecting the user to the "dash.php" if login is successful or printing an error if not. However whenever I submit the form, it just reloads the login.php... Did I make a stupid error somewhere or am I missing something? Sorry about the huge post!
login.php (containing form):
//Form Action
<?php
error_reporting(E_ALL);
ini_set('display_errors','1');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require ('scripts/mysqli_connect.php');
require ('scripts/login_functions.php');
list ($check, $data) = check_login($dbc, $_POST['username'], $_POST['password']);
if($check) {
redirect_user('dash.php');
} else {
$errors = $data;
}
mysqli_close($dbc);
}
?>
// Website HTML
//Form
<form class="contact-form" method="post" action="login.php">
<div class="col-sm-5 col-sm-offset-1">
<div class="form-group">
<label>Username: </label>
<input type="text" name="username" id="username" size="15" class="form-control" required="required" placeholder="username">
</div>
<div class="form-group">
<label>Password: </label>
<input type="password" name="password" id="password" size="15" class="form-control" required="required" placeholder="password">
</div>
<div class="form-group">
<input type="submit" name="submit" value="Login" />
</div>
</div>
</form>
login_functions.php:
<?php
function redirect_user ($page = '../login.php') {
$url = "http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
$url = rtrim($url, '/\\');
$url .= '/' . $page;
//Redirect User
header("Location: $url");
exit(); //Quit the script.
}
function check_login($dbc, $username = '', $password = '') {
$errors = array();
if(empty($username)) {
$errors[] = 'You forgot to enter your username.';
} else {
$u = mysqli_real_escape_string($dbc, trim($username));
}
if(empty($password)) {
$errors[] = 'you forgot to enter your passord.';
} else {
$p = mysqli_real_escape_string($dbc, trim($password));
}
if (empty($errors)) {
$q = "SELECT username, password FROM users WHERE username='$u' AND password=sha1('$p')";
$r = #mysqli_query ($dbc, $q);
//Check Results
if(mysqli_num_rows($r) == 1) {
$row = mysqli_fetch_array ($r, MYSQLI_ASSOC);
return array(true, $row);
} else {
$errors[] = 'The username/password combination is incorrect.';
}
}
}
?>
You are not returning you errors:
return array(true, $row);
} else {
$errors[] = 'The username/password combination is incorrect.';
$return array(false, $errors);
}
And you are not displaying your errors:
// Website HTML
<?php if ($errors):?>
<?php echo '<p>' . implode('</p><p>', $errors) . '<p>';?>
<?php endif;?>
//Form
<form class="contact-form" method="post" action="login.php">

Categories