How to set session userdata from database in codeigniter? - php

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

Related

how to get match only one username and password in array

$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;
}

Error create login using codeigniter V.3

I am trying to migrate from CodeIgniter version 2 to version 3 , but when I try to log it turns out there is a problem, but the same script and when it is run versioned 2 there is no problem ? there anything you can help
This my error
A PHP Error was encountered
Severity: Notice
Message: Undefined index: username
Filename: controllers/login.php
Line Number: 27
This my controllers
class Login extends CI_Controller {
function __construct() {
parent::__construct();
}
function index($param='') {
if($param == 'error')
$param == 'Incorrect username or password';
if($param == 'error1')
param == 'User not acctive';
$data = array('title'=>'KOPKAR - Login','message'=>$param,'base_url'=>base_url());
$this->load->view('login/login', $data);
}
public function do_login() {
$data = $this->input->post(null,true);
$is_login = $this->db->get_where('user',array(
'username'=>$data['username'],
'password'=>md5(trim($data['password']))
))->row();
if($is_login){
$session_set = array(
'is_login' => true,
'nik' => $is_login->nik,
'username' => $is_login->username,
'id_user' => $is_login->id_user,
'lastlogin' => $is_login->lastlogin,
'jabatan' => $is_login->jabatan
);
$this->db->update('user',array('lastlogin'=>date('Y-m-d H:i:s')),array('id_user'=>$is_login->id_user));
$this->session->set_userdata($session_set);
redirect('home');
}else{
redirect('login/index/error');
}
}
}
check this
public function do_login() {
$username = $this->input->post('username');
$password = $this->input->post('password');
$is_login = $this->db->get_where('user',array(
'username'=>$username,
'password'=>md5(trim($password))
))->row();
if($is_login){
$session_set = array(
'is_login' => true,
'nik' => $is_login->nik,
'username' => $is_login->username,
'id_user' => $is_login->id_user,
'lastlogin' => $is_login->lastlogin,
'jabatan' => $is_login->jabatan
);
$this->db->update('user',array('lastlogin'=>date('Y-m-d H:i:s')),array('id_user'=>$is_login->id_user));
$this->session->set_userdata($session_set);
redirect('home');
}else{
redirect('login/index/error');
}
i'm adding this
$username = $this->input->post('username');
$password = $this->input->post('password');
and remove this
$data = $this->input->post(null,true);

warning if register with email / username is already registered

I tried to make the project regrister using CodeIgniter framework , with verification email after list and it can be used. but there is weakness in my scirpt . when the register if he is using the same user then when submitted will appear statement that "you 've registered email" .. what should I add to controllers login.
function submit() {
//passing post data dari view
$_POST['dob'] = $_POST['year'].'-'.$_POST['month'].'-'.$_POST['day'];
$firstname = $this->input->post('firstname');
$lastname = $this->input->post('lastname');
$password = $this->input->post('password');
$email = $this->input->post('email');
$dob = $this->input->post('dob');
$jkl = $this->input->post('jkl');
$lastlogin = $this->input->post('lastlogin');
//memasukan ke array
$data = array(
'firstname' => $firstname,
'lastname' => $lastname,
'password' => $password,
'email' => $email,
'dob' => $dob,
'jkl' => $jkl,
'lastlogin' => $lastlogin,
'active' => 0
);
//tambahkan akun ke database
$this->m_register->add_account($data);
//redirect(base_url().'homepage/homepage');
$id = $this->m_register->add_account($data);
//enkripsi id
$encrypted_id = md5($id);
$this->load->library('email');
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.gmail.com',
'smtp_port' => 465,
'smtp_user' => '*******#*****esy.com ',
'smtp_pass' => '**********',
'mailtype' => 'html',
'charset' => 'utf-8',
'wordwrap' => TRUE
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$email_setting = array('mailtype'=>'html');
$this->email->initialize($email_setting);
$this->email->from('jobrecruit#jobrecruit.esy.es', 'JOBRECRUIT');
$this->email->to($email);
$this->email->subject('Confirmation Email');
$this->email->message("WELCOME TO JOB RECRUIT <br><p></p>Hallo $firstname $lastname <br><br><br><p>Terimakasih telah melakuan registrasi dengan:<br><br><p>
Username = $email<p>
Password = $password
<br><br>
<p>
untuk memverifikasi akun silahkan klik tautan dibawah ini</p><br><br>"
.site_url("login/register/verification/$encrypted_id")."
<br><br><br>
<p></p><br>
<p>Thanks</p>Admin JOBRECRUIT");
if($this->email->send())
{
$data = array ( 'isi' => 'login/vsuccess');
$this->load->view('layout/wrapper',$data);
}else
{
$data = array ( 'isi' => 'login/vgagal');
$this->load->view('layout/wrapper',$data);
}
}
I will suggest you to use form validation library of codeigniter.
function submit() {
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','trim|required|valid_email|xss_clean|is_unique[TABLE_NAME.email]');
$this->form_validation->set_message('is_unique', 'you have registered email.');
if($this->form_validation->run())
{
//passing post data dari view
$_POST['dob'] = $_POST['year'].'-'.$_POST['month'].'-'.$_POST['day'];
$firstname = $this->input->post('firstname');
$lastname = $this->input->post('lastname');
$password = $this->input->post('password');
$email = $this->input->post('email');
$dob = $this->input->post('dob');
$jkl = $this->input->post('jkl');
$lastlogin = $this->input->post('lastlogin');
//memasukan ke array
$data = array(
'firstname' => $firstname,
'lastname' => $lastname,
'password' => $password,
'email' => $email,
'dob' => $dob,
'jkl' => $jkl,
'lastlogin' => $lastlogin,
'active' => 0
);
//tambahkan akun ke database
$this->m_register->add_account($data);
//redirect(base_url().'homepage/homepage');
$id = $this->m_register->add_account($data);
//enkripsi id
$encrypted_id = md5($id);
$this->load->library('email');
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.gmail.com',
'smtp_port' => 465,
'smtp_user' => 'jobrecruit#jobrecruit.esy.es ',
'smtp_pass' => 'jobrecruit123456',
'mailtype' => 'html',
'charset' => 'utf-8',
'wordwrap' => TRUE
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$email_setting = array('mailtype'=>'html');
$this->email->initialize($email_setting);
$this->email->from('jobrecruit#jobrecruit.esy.es', 'JOBRECRUIT');
$this->email->to($email);
$this->email->subject('Confirmation Email');
$this->email->message("WELCOME TO JOB RECRUIT <br><p></p>Hallo $firstname $lastname <br><br><br><p>Terimakasih telah melakuan registrasi dengan:<br><br><p>
Username = $email<p>
Password = $password
<br><br>
<p>
untuk memverifikasi akun silahkan klik tautan dibawah ini</p><br><br>"
.site_url("login/register/verification/$encrypted_id")."
<br><br><br>
<p></p><br>
<p>Thanks</p>Admin JOBRECRUIT");
if($this->email->send())
{
$data = array ( 'isi' => 'login/vsuccess');
$this->load->view('layout/wrapper',$data);
}else
{
$data = array ( 'isi' => 'login/vgagal');
$this->load->view('layout/wrapper',$data);
}
}
}
Error message will be accessible in form_validation() or for specific form_error('email') print as it is on view to show error message
In Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct(){
parent::__construct();
// if($this->session->userdata('user'))redirect('homepage/menu');
}
public function index($param='')
{
if($param == 'error')
$param = 'Incorrect username or password';
if($param == 'error1')
$param = 'User not acctive';
$data = array('title'=>'Login','message'=>$param, 'isi' => 'login/vlogin', 'base_url'=>base_url());
$this->load->view('layout/wrapper', $data);
}
public function do_login() {
$mail = $_POST['mail'];
$password = $_POST['password'];
$result = $this->Model_name->check_valid_user($mail,$password);
if ($result == 1)
{ //User exists
if ($result['active'] == 1)
{
//User exists and his email is verified
$session_set = array(
'user' => true,
'firstname' => $user->firstname,
'lastname' => $user->lastname,
'jkl' => $user->jkl,
'id' => $user->id,
'lastlogin' => $user->lastlogin
);
$this->Model_name->update_last_login($result['id']);
$this->session->set_userdata($session_set);
redirect('homepage/menu');
}
else
{
//User exists BUT his email is NOT verified
$this->session->set_flashdata('message', 'Akun anda belum aktif silahkan cek email anda untuk verifikasi');
//You have to capture and show the flash message in view
redirect('login/login/index');
}
}
else
{
//User does NOT exist at all
$this->session->set_flashdata('message', 'Username dan Password tidak sama.');
//You have to capture and show the flash message in view
redirect('login/login/index');
}
}
}
In Model
public function check_valid_user($mail,$password)
{
$query = $this->db->quesry("SELECT * FROM user WHERE mail='$mail' AND password = '$password'");
$result = $query->result_array();
$count = count($result);
if(empty($count) || $count >1 )
{
$log = 0;
return $log;
}
else
{
$log = 1;
return $log;
}
}
function update_last_login($id)
{
$data = array(
'lastlogin' => date('Y-m-d H:i:s')
);
$this->db->where('id', $id);
$this->db->update('user', $data);
}

db escape in codeigniter

I want to be able to use codeigniter db escape because it hashes my passwords OK but in the password row it adds two quotes on either side Example 'demo1234'
My salt row does not show it which is OK just the password. On password how do I use my db escape but not having the quotes show up on password row in db.
public function addUserToDatabase() {
$this->load->helper('date');
$username = $this->input->post('username');
$email = $this->input->post('email');
$password = $this->input->post('password');
$this->db->escape($salt = substr(md5(uniqid(rand(), true)), 0, 9)); // Works OK
// Salt does not work if don't use db escape.
$password = $this->db->escape(sha1($salt . sha1($salt . sha1($password)))); // 'demo1234' shows quotes either side off password
$data = array(
'user_id' => "1",
'user_group_id' => "1",
'username' => $username,
'email' => $email,
'salt' => $salt,
'password' => $password,
'ip' => $this->input->ip_address(),
'status' => "1",
'date_added' => mdate('%Y-%m-%d %H:%i:%s', now())
);
$this->db->insert('user', $data);
}
I worked it out I had to do it like this below, all done.
public function addUserToDatabase() {
$this->load->helper('date');
$username = $this->input->post('username');
$email = $this->input->post('email');
$this->db->escape($password = sha1($salt . sha1($salt . sha1($this->input->post('password')))));
$this->db->escape($salt = substr(md5(uniqid(rand(), true)), 0, 9));
$data = array(
'user_id' => "1",
'user_group_id' => "1",
'username' => $username,
'email' => $email,
'salt' => $salt,
'password' => $password,
'ip' => $this->input->ip_address(),
'status' => "1",
'date_added' => mdate('%Y-%m-%d %H:%i:%s', now())
);
$this->db->insert('user', $data);
}

codeigniter array variable

Here is my code so far, it all works except when I try to make 'company' = $company there's something im missing, and id love to know what
if($query) // if the user's credentials validated///
{
$this->db->where('username');
$this->db->select('company');
$company = $this->db->get('user');
$data = array(
'username' => $this->input->post('username'),
'company' => $company
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('site/members_area');
}
else
{
$this->index();
}
Both the other answers fix one of the two errors in your code, this is an addition.
if($query) {
$username = $this->input->post('username');
$this->db->select('company')->where('username', $username);
$result = $this->db->get('user')->row_array();
$data = array(
'username' => $username,
'company' => $row['company'],
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('site/members_area');
} else {
$this->index();
}
See what I did there? You don't need to use result_array() then grab $query_result[0] as row_array() does that for you. And with a little method chaining thrown in for good measure you can clean up your syntax.
There is a missing comma after "$company".
EDIT: Based on the discussion in the comments, I've rewritten your code to (hopefully) get the value of the company:
if($query) {
$username = $this->input->post('username');
$this->db->where('username', $username);
$this->db->select('company');
$result = $this->db->get('user');
// Here we assume that the query succeeded.
// You should probably double-check.
$company = $result->result_array[0]['company'];
$data = array(
'username' => $username,
'company' => $company,
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('site/members_area');
} else {
$this->index();
}
result_array is a function, not a variable. Try
if($query) {
$username = $this->input->post('username');
$this->db->where('username', $username);
$this->db->select('company');
$query_result = $this->db->get('user');
// Here we assume that the query succeeded.
// You should probably double-check.
$result= $query_result->result_array();
$data = array(
'username' => $username,
'company' => $result[0]['company'],
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('site/members_area');
} else {
$this->index();
}

Categories