how to get match only one username and password in array - php

$data = array(
array(
'username' => 'bharatbhai#gmail.com',
'password' => '12345'
),
array(
'username' => 'test#gmail.com',
'password' => '8520'
),
array(
'username' =>'abc#gmail.com',
'password' => '123123'
)
);
and my condition is here
my task is only match one username to one password
but i got error
$check_email = false;
if(array_search($email,array_column($data,'username')) !== FALSE){
$check_email = true;
}
$check_pass = false;
if(array_search($password,array_column($data,'password')) !== FALSE){
$check_pass = true;
}
if(!empty($check_email) && !empty($check_pass)){
echo "<h2>Email and Password matched</h2>";
}
else{
echo '<h2>Oh no email and password not matched.</h2>';
i am match my condition using array_column funcation.

You need to update your logic which checks if both username and password are same in each sub array. I made quick logic you should apply to your code.
<?php
$email = "bharatbhai#gmail.com";
$password = "12345";
$data = array(
array(
'username' => 'bharatbhai#gmail.com',
'password' => '12345'
),
array(
'username' => 'test#gmail.com',
'password' => '8520'
),
array(
'username' =>'abc#gmail.com',
'password' => '123123'
)
);
$hasSameMailAndPass = false;
foreach($data as $key => $value){
if($value["username"] == $email and $value["password"] == $password){
$hasSameMailAndPass = true;
}
}
if($hasSameMailAndPass){
echo "<h2>Email and Password matched</h2>";
} else {
echo '<h2>Oh no email and password not matched.</h2>';
}
?>

I think you can perform a multilevel conditional check.
Actually it seems you search the existancce of the email and of the password, but not actually for the same user.
Does this email exits? yes or no?
does this passwrod exists? yes or no?
Actually should be the following:
does this email exists? yesr or no?
if yes, does that email fit with this password? yes or no?
So you could check if a user exists and has right credentials
$data = array(
array(
'username' => 'bharatbhai#gmail.com',
'password' => '12345'
),
array(
'username' => 'test#gmail.com',
'password' => '8520'
),
array(
'username' =>'abc#gmail.com',
'password' => '123123'
)
);
/**
* #param array $login array('email'=> 'loginemail', 'password'=> 'loginpwd')
* #return bool
*/
function canBeAuthenticate(array $data, array $login)
{
$hasMail = false;
$userIndex = null;
# check if email exists in system
# if not, not even check pwd and return false
# if exites, get ID of user and then check pwd
foreach ($users as $index => $userData) {
if ( $userData == $login['email'] ) {
$hasMail = true;
$userIndex = $index;
}
}
if (!$hasMail) {
echo 'Email not in system';
return false;
}
if ($data[$userIndex]['password'] == $login['password']) {
echo 'Match';
return true;
}
echo 'wrong password';
return false;
}

Related

remember me checkbox in login using cookie in codeignitor

i want to save email and password on clicking remember me checkbox and cookie should get set on remember me.login is working fine. kindly help me with my code in codeignitor here is my controller code:
public function loginaction()
{
$email=$this->input->post('email');
$password=$this->input->post('password');
$where = array('email'=>$email,'password'=>$password);
$tbname='login';
$query = $this->Insert_Model->viewdata($tbname,$where);
if(empty($query))
{
$data['msg']="Invalid email or password";
$this->load->view('login',$data);
}
else
{
redirect('dashboardv1');
}
}
below is cookie code which i implemented:
function set()
{
$cookie= array(
'name' => 'chkremember',
'value' => 'test',
'expire' => '300',
'secure' => TRUE
);
$this->input->set_cookie($cookie);
}
function get()
{
echo $this->input->cookie('chkremember',true);
}
firstly you have to include cookie helper as I mention in the comment section
After that in your controller
public function loginaction()
{
$this->load->helper('cookie');
$email=$this->input->post('email');
$password=$this->input->post('password');
$where = array('email'=>$email,'password'=>$password);
$tbname='login';
$query = $this->Insert_Model->viewdata($tbname,$where);
if(empty($query))
{
$data['msg']="Invalid email or password";
$this->load->view('login',$data);
}
else
{
//first you have to delete old cookie and create new one
delete_cookie("email");
delete_cookie("password");
if ($this->input->post('remember') == 'true') {
$userName = array(
'name' => 'email',
'value' => YOUREMAIL,
'expire' => '86500',
'prefix' => '',
'secure' => FALSE
);
$this->input->set_cookie($userName);
$password = array(
'name' => 'password',
'value' => YOURPASSWORD,
'expire' => '86500',
'prefix' => '',
'secure' => FALSE
);
$this->input->set_cookie($password);
}
redirect('dashboardv1');
}
}
Get the cookie you can use below code
<?php echo get_cookie('email'); ?>
<?php echo get_cookie('password'); ?>

Why the sql query to update password in not running in a php script of a webpage?

I am creating a website which have two database table of client and freelancer. Now i have to integrate everything, like profile credentials, password, images etc.
initially the application have two different files(in two different folders) that handels. The change in passwords and other profile credentials such as name, username and email of freelancer and client.
So to integrate everything into single file, i am executing all the sql queries of freelancer table in the client one. All the profile credentials get updated successfully, but not the password. I dont understand why?
This is Client/profile.php file
$client = new Client();
$freelancer = new Freelancer();
//Check if Client is logged in
if (!$client->isLoggedIn() && !$freelancer->isLoggedIn()) {
Redirect::to('../index.php');
}
//Get Instructor's Data
$query = DB::getInstance()->get("client", "*", ["clientid" => $client->data()->clientid]);
if ($query->count()) {
foreach ($query->results() as $row) {
$nid = $row->id;
$name = $row->name;
$username = $row->username;
$email = $row->email;
$bgimage = $row->bgimage;
$phone = $row->phone;
}
}
//Edit Profile Data
if (isset($_POST['profile'])) {
if (Input::exists()) {
if (Token::check(Input::get('token'))) {
$errorHandler = new ErrorHandler;
$validator = new Validator($errorHandler);
$validation = $validator->check($_POST, [
'username' => [
'required' => true,
'maxlength' => 20,
'minlength' => 2
],
'name' => [
'required' => true,
'maxlength' => 100,
'minlength' => 2
],
'email' => [
'required' => true,
'maxlength' => 255,
'email' => true,
],
'phone' => [
'required' => false,
'maxlength' => 10,
'minlength' => 10
]
]);
if (!$validation->fails()) {
$client->update([
'name' => Input::get('name'),
'username' => Input::get('username'),
'email' => Input::get('email'),
'phone' => Input::get('phone')
], [
'clientid' => $client->data()->clientid
]);
if (count($client) > 0) {
$noError = true;
}
else {
$hasError = true;
}
$freelancer->update([
'name' => Input::get('name'),
'username' => Input::get('username'),
'email' => Input::get('email'),
'phone' => Input::get('phone')
], [
'freelancerid' => $freelancer->data()->freelancerid
]);
if (count($freelancer) > 0) {
$noError = true;
} else {
$hasError = true;
}
}
else {
$error = '';
foreach ($validation->errors()->all() as $err) {
$str = implode(" ", $err);
$error .= '
<div class="alert alert-danger fade in">
×
<strong>Error!</strong> ' . $str . '
</div>
';
}
}
}
}
}
/*Edit Password Data*/
if (isset($_POST['register'])) {
if (Input::exists()) {
if (Token::check(Input::get('token'))) {
$errorHandler = new ErrorHandler;
$validator = new Validator($errorHandler);
$validation = $validator->check($_POST, [
'password_current' => [
'required' => true,
'maxlength' => 300
],
'password_new' => [
'required' => true,
'minlength' => 6
],
'password_new_again' => [
'required' => true,
'match' => 'password_new'
]
]);
if (!$validation->fails()) { //working fine
if ( (Hash::make(Input::get('password_current'), $client->data()->salt) !== $client->data()->password) && (Hash::make(Input::get('password_current'), $freelancer->data()->salt) !== $freelancer->data()->password) ){
$hasError = true;
}
else {
$salt = Hash::salt(32);
$changed_password = Hash::make(Input::get('password_new'), $salt);
$client->update([
'password' => $changed_password,
'salt' => $salt
], [
'clientid' => $client->data()->clientid
]);
$noError = true;
}
if (!$validation->fails()) { //not working
if (Hash::make(Input::get('password_current'), $freelancer->data()->salt) !== $freelancer->data()->password) {
$hasError = true;
}
else {
$salt = Hash::salt(32);
$freelancer->update([
'password' => Hash::make(Input::get('password_new'), $salt),
'salt' => $salt
],[
'freelancerid' => $freelancer->data()->freelancerid
]);
$noError = true;
}
}
else {
$error = '';
foreach ($validation->errors()->all() as $err) {
$str = implode(" ", $err);
$error .= '
<div class="alert alert-danger fade in">
×
<strong>Error!</strong> ' . $str . '
</div>
';
}
}
}
}
}
This is Freelancer/profile.php file code to change password
if(isset($_POST['register'])){
if (Input::exists()) {
if (Token::check(Input::get('token'))) {
$errorHandler = new ErrorHandler;
$validator = new Validator($errorHandler);
$validation = $validator->check($_POST, [
'password_current' => [
'required' => true,
'maxlength' => 300
],
'password_new' => [
'required' => true,
'minlength' => 6
],
'password_new_again' => [
'required' => true,
'match' => 'password_new'
]
]);
if (!$validation->fails()) {
if (Hash::make(Input::get('password_current'), $freelancer->data()->salt) !== $freelancer->data()->password) {
$hasError = true;
}
else {
$salt = Hash::salt(32);
$freelancer->update([
'password' => Hash::make(Input::get('password_new'), $salt),
'salt' => $salt
],[
'freelancerid' => $freelancer->data()->freelancerid
]);
$noError = true;
}
}
else {
$error = '';
foreach ($validation->errors()->all() as $err) {
$str = implode(" ",$err);
$error .= '
<div class="alert alert-danger fade in">
×
<strong>Error!</strong> '.$str.'
</div>
';
}
}
}
}
}
My question is if the query to change username, email and phone number is working fine, why the password change for freelancer is not working?
The hash function algorithm can give two encrypted strings for a same inputed string so when i am calling the function two times for the client and the freelancer, two different strings and getting stored in the data base.

Trouble with arrays and foreach php oop

Basically I'm trying to create a login, the email validation doesn't seem to pass. I've been looking around for an example but I'm genuinely not sure, doing it statically seems easy enough, however I vaguely suspect using static method would be incorrect to use as a login method(perhaps I'm over thinking it)
<?php
require ("Database.class.php");
class Login
{
private
$email,
$password,
$database,
$db = null;
public function __construct()
{
$this->db = new Database;
}
public function validEmail($email)
{
return (filter_var($email, FILTER_VALIDATE_EMAIL) !== FALSE);
}
public function emptyPassword($password)
{
return(empty($password) !== TRUE);
}
public function validPassword($password)
{
$query = $this->db->prepare("select * from username");
return $query->fetch(PDO::FETCH_ASSOC);
}
}
<?php
require "classes/Login.class.php";
require "loadclasses.php";
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$email = $pass = "";
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$email = $post['email-login'];
$pass = $post['password-login'];
$errors = array();
$fields = array(
'email-login' => array(
'validate' => 'validEmail',
'message' => 'Enter a valid email address'
),
'password-login' => array(
'validate' => 'emptyPassword',
'message' => 'Password required'
)
);
$login = new Login();
foreach($fields as $key => $value)
{
$validation_result = $login->$value['validate']($value);
if(!$validation_result)
{
$errors[] = ['name' => $key, 'error' => $value['message']];
}
}
if(empty($errors))
{
$success = ['response' => 'true'];
session_start();
}
}
header('Content-Type: application/json');
if (empty($errors))
{
echo json_encode($success);
}
else
{
echo json_encode(["errors" => $errors]);
}
As mentioned I'm aware I could do something similar to this:
$errors = array();
$fields = array(
'username' => array(
'validator' => 'validateUsername',
'message' => 'Username must be between three and fourteen alphanumeric characters'
),
'email' => array(
'validator' => 'validateEmail',
'message' => 'Please enter a valid email',
),
'password' => array(
'validator' => 'validatePassword',
'message' => 'Password must be a minimum of seven characters'
)
);
if(!Validation::validateRepeatPassword($password, $repeatPassword))
{
$errors[] = ["name" => "repeatPassword", "error" => "Passwords must match"];
}
foreach($post as $key => $value)
{
if(isset($fields[$key]))
{
if(!Validation::{$fields[$key]['validator']}($value))
{
$errors[] = ['name' => $key, 'error' => $fields[$key]['message']];
}
}
}
The main problem as I mentioned is I'm fairly sure that would be the wrong way to approach this problem
The problem seems to be here:
$validation_result = $login->$value['validate']($value);
When you do that, you're actually passing $value which is an array (according to the foreach). You're not actually passing the email
So, according to your code, you should change your validation array to something like:
$fields = array(
'email-login' => array(
'validate' => 'validEmail',
'message' => 'Enter a valid email address',
'value' => $email,
),
'password-login' => array(
'validate' => 'emptyPassword',
'message' => 'Password required',
'value' => $pass,
)
);
And then, change your validation line to:
$validation_result = $login->$value['validate']($value['value']);

OOP validation PHP

Currently I'm trying to validate an email address via OOP php with arrays so I can add additional functions later, however when I insert a valid email address the validation still fails, I think perhaps my arrays are set up wrong but I'm not entirely sure, additionally I had tried different different operators to check if the email function would output different results however as mentioned it always seems to fail, any advice would be appreciated
class Login
{
private
$email,
$password,
$database,
$db = null;
public function __construct()
{
$this->db = new Database;
}
public function validEmail($email)
{
return (filter_var($email, FILTER_VALIDATE_EMAIL) !== FALSE);
}
}
<?php
require "classes/Login.class.php";
$validate = new Login();
require "loadclasses.php";
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$email = $pass = "";
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$email = $post['email-login'];
$pass = $post['password-login'];
$errors = array();
$fields = array(
'email-login' => array(
'validate' => 'validEmail',
'message' => 'Enter a valid email address'
)
);
foreach($fields as $key => $value)
{
if(isset($fields[$key]))
{
$errors[] = ['name' => $key, 'error' => $fields[$key]['message']];
}
}
if(empty($errors))
{
$success = ['response' => 'true'];
session_start();
}
}
header('Content-Type: application/json');
if (empty($errors))
{
echo json_encode($success);
}
else
{
echo json_encode(["errors" => $errors]);
}
As already mentioned in comments - you don't use functions from your Login class.
So, how you current code works:
$fields = array(
'email-login' => array(
'validate' => 'validEmail',
'message' => 'Enter a valid email address'
)
);
foreach($fields as $key => $value)
{
// isset($fields[$key]) is ALWAYS true
if(isset($fields[$key]))
{
$errors[] = ['name' => $key, 'error' => $fields[$key]['message']];
}
}
What you really should do is something like:
$fields = array(
'email-login' => array(
'validate' => 'validEmail',
'message' => 'Enter a valid email address'
)
);
// instantiate object of Login class
$login = new Login();
foreach($fields as $key => $value)
{
// call a function `$value['validate']` (it is `validEmail`)
$validation_result = $login->{$value['validate']}($email);
// if validation fails - add error message
if(!$validation_result)
{
$errors[] = ['name' => $key, 'error' => $value['message']];
}
}
And btw $post is a wrong variable name, I suppose it is $_POST.

How to set session userdata from database in codeigniter?

I have problem with my session login in codeigniter 3. I can't get data from database to insert session. Whats wrong with my code?
My Controller
function __construct(){
parent::__construct();
$this->load->model('m_login');
}
function index(){
$this->load->view('v_login');
}
function aksi_login(){
$username = $this->input->post('username');
$password = $this->input->post('password');
$where = array(
'username' => $username,
'password' => md5($password)
);
$cek = $this->m_login->cek_login("admin",$where)->num_rows();
if($cek > 0){
$data_session = array(
'username' => $cek['username'],
'nama' => $cek['nama']
'status' => "login"
);
$this->session->set_userdata($data_session);
redirect(base_url("admin"));
}else{
echo "Username dan password salah !";
}
}
}
My Model
<?php
class M_login extends CI_Model{
function cek_login($table,$where){
return $this->db->get_where($table,$where);
}
}
1.m_login->cek_login
this functions returns a SQL QUERY OBJECT
2.the SQL QUERY OBJECT ->num_rows() function returns a INT ($cek)
3.so $cek is a INT . so u cant use like an array ($cek['username'])
so Please try this code
function aksi_login(){
$username = $this->input->post('username');
$password = $this->input->post('password');
$where = array(
'username' => $username,
'password' => md5($password)
);
$cek = $this->m_login->cek_login("admin",$where);//$cek is a Query Object
$rows = $cek->num_rows();//$rows is a INT
if($rows > 0){
$cek = $cek->row_array();//now u get an Array
$data_session = array(
'username' => $cek['username'],
'nama' => $cek['nama']
'status' => "login"
);
$this->session->set_userdata($data_session);
redirect(base_url("admin"));
}else{
echo "Username dan password salah !";
}
}
Try This
if($cek > 0){
$cek = $cek->row_array();
$data_session = array(
'username' => $cek['username'],
'nama' => $cek['nama']
'status' => "login"
);
$this->session->set_userdata($data_session);
redirect(base_url("admin"));
}else{
echo "Username dan password salah !";
}
Try like this...
In codeigniter row_array() takes the first matched row in array format.So your function aksi_login() must be like this...
function aksi_login(){
$username = $this->input->post('username');
$password = $this->input->post('password');
$where = array(
'username' => $username,
'password' => md5($password)
);
$result = $this->m_login->cek_login("admin",$where);
$cek = $this->m_login->cek_login("admin",$where)->num_rows();
if($cek > 0){
$cek = $result->row_array();//no your records are in array format having matched row
$data_session = array(
'username' => $cek['username'],
'nama' => $cek['nama']
'status' => "login"
);
$this->session->set_userdata($data_session);
redirect(base_url("admin"));
}else{
echo "Username dan password salah !";
}
}
For more refer here..https://www.codeigniter.com/userguide3/database/results.html

Categories