Set session values with query result in CodeIgniter 3 - php

I have a function in my model that checks the credentials given in the login form. It selects the email, senha and tipo_pessoa. Below is the function:
public function find_credentials()
{
$this->db
->select('email, senha, tipo_pessoa')
->from($this->table)
->where('email', $this->input->post('email'))
->where('senha', md5($this->input->post('password')));
$query = $this->db->get();
if ($query->num_rows() == 1) {
return true;
}
return false;
}
The next function, located in my Controller, is executed regardless of the results of the previous function. It decides what to do depending on the returned result:
public function validate_credentials()
{
if ($this->Usuarios_fisica_model->find_credentials()) {
$data = array();
$data['email'] = $this->input->post('email');
$this->session->set_userdata($data);
$this->session->set_flashdata('message', 'Bem-vindo!');
redirect('/', 'refresh');
} else {
$this->session->set_flashdata('message', 'Desculpe, credenciais inválidas');
redirect('/');
}
}
I need to store tipo_pessoa in the session to determine which page the user should be redirected to. I have two different tables for two different kind of users, and each kind has its own page.
Edit*
After the suggested solutions, I added to my header file the following code to echo the tipo_pessoa:
<div class="menu_login">
<?php if ($this->session->userdata('email')) { ?>
<span><?php echo $this->session->userdata('email'); ?></span>
<span><?php echo $this->session->userdata('tipo_pessoa'); ?></span>
Ir ao Painel
Sair
<?php } else { ?>
<span>Minha Conta</span>
Entre
Cadastre-se
<?php } ?>
</div>

Use this changes in Model:
$query = $this->db->get();
return $query->result();
and make this changes to controller:
$data = $this->Usuarios_fisica_model->find_credentials();
if(!empty($data))
{
$tipo_pessoa = $data[0]['tipo_pessoa']; //Get value of tipo_pessoa
$this->session->set_userdata('tipo_pessoa', $tipo_pessoa);//Set value in session
//your if part code
}
else
{
//your else part code
}

Here's an example of how to set session data from the results of a query:
function get_something()
{
$this->db->select('something');
$something = $this->db->get('table')->row();
$this->session->set_userdata('something',$something);
}
With your example model:
$this->db
->select('email, senha, tipo_pessoa')
->from($this->table)
->where('email', $this->input->post('email'))
->where('senha', md5($this->input->post('password')));
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result_array();
}
return false;
controller:
if ($something = $this->Usuarios_fisica_model->find_credentials()) {
$data = array();
$data['email'] = $this->input->post('email');
$this->session->set_userdata('tipo_pessoa', $something['tipo_pessoa']);
$this->session->set_userdata($data);
$this->session->set_flashdata('message', 'Bem-vindo!');
redirect('/', 'refresh');
} else {
$this->session->set_flashdata('message', 'Desculpe, credenciais inválidas');
redirect('/');
}

Instead of doing what I intended to do, I simply put a select box in the login page to choose between the two different types. Now it is easy to retrieve the value and make the choices.

Related

Not loading view by calling method

I made a user table that will link to his postings when he submits a post. (It parts works correctly)
So I have been trying to create a method in codeigniter 3. I have it set to where if the user is logged in and clicks his user name it will show all his submissions, by simply pulling from the table his user_id and then looping through his posts.
Well, I have two issues
when I enter in the url to call this function it wants a value for the uri. Example: localhost/CI/controller/account yet it will not load until I put something after account (account is the method name).
Like localhost/CI/controller/account/9
Also this function does not seem to work either for some reason, I do not know if it has something to do with it wanting another value.
I have researched this for the past hour with no luck.
Controller:
public function account(){
$data['title'] = 'Your submissions';
$data['posts'] = $this->post_model->user_posts();
$this->load->view('templates/header');
$this->load->view('users/profile', $data);
$this->load->view('templates/footer');
}
//view function the post by clicking on title
public function view ($slug=NULL){
$data['post'] = $this->post_model->get_posts($slug);
$post_id = $data['post']['id'];
$data['comments'] = $this->comment_model->get_comments($slug);
if(empty($data['post'])){
show_404();
}
$data['title'] = $data['post']['title'];
$this->load->view('templates/header');
$this->load->view('posts/view', $data);
$this->load->view('templates/footer');
}
Model:
public function user_posts (){
$usernum = $this->session->userdata('customer_id');
$this->db->order_by('created_time','DESC');
$query = $this->db->get_where('posts',array('customer_id ='=>'$usernum'));
return $query->result_array();
}
$query = $this->db->get_where('posts',array('slug'=>$slug));
return $query->row_array();
}
View:
<?php
echo $title;
foreach ($posts as $post): {
echo $post['title'];
}endforeach;
?>
Controller :
public function account($acno = "") {//changes
$data['title'] = 'Your submissions';
$data['posts'] = $this->Post_model->user_posts();//changes
echo'<pre>';print_r($data);die;//changes
$this->load->view('templates/header');
$this->load->view('users/profile', $data);
$this->load->view('templates/footer');
}
Model :
public function user_posts() {
$usernum = $this->session->userdata('customer_id');
$this->db->order_by('created_time', 'DESC');
$query = $this->db->get_where('posts', array('customer_id =' => $usernum));//changes
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return array();
}
}
Change model function like this
public function user_posts (){
$usernum = $this->session->userdata('customer_id');
$this->db->order_by('created_time','DESC');
$query = $this->db->get_where('posts', array('customer_id' => $usernum));
return $query->result_array();
}
The associative array does not need = in where() or get_where() to get the record
Do not need single quotes with $usernum
After trying somethings this is what corrected my issues
Public function user_posts (){
$this->db->order_by('created_time','DESC');
$query = $this->db->get_where('posts', array('customer_id' => $this->session->userdata('customer_id')));
return $query->result_array();
}
I believe by removing the $usernum = $this->session->userdata('customer_id'); and adding it to the query, now allows the user to call his own session id without the need to enter one into the function.
Thanks to those that gave me input
I dont know how your button click is set up but this is how you should do it.
Button click page
<?= site_url(); ?>controller_name/account
account function in controller
function account(){
//1. Check if user is Logged in
if (!$this->ion_auth->logged_in())
{
//If they are not logged in, redirect them to login page or do something
}
else{
//User is logged in so get submissions
//Get all submissions
$data['title'] = 'Your submissions';
$this->data['posts']= $this->post_model->user_posts();
$this->load->view('templates/header');
$this->load->view('users/profile', $data);
$this->load->view('templates/footer');
}}
User posts function in Model
function user_posts (){
$user = $this->ion_auth->user()->row();
$ref_id=$user->id; //Gets you user id
$this->db->where(['customer_id'=>$ref_id]);
$this->db->order_by('created_time','DESC');
$query=$this->db->get('posts');
if($query->result())
{
return $query->result();
}
else
{
return false;
}}
Also, consider using Ion Auth for your login in codeigniter as it allows you access session data easily without issues as the one you've been facing.

password_verify() logging in all the time

Using codeigniter hashed my password with BCRYPT, seems that everytime I login I redirect to the success page. So I am figuring password verify is not working, even if I enter the incorrect login it still redirects, does not throw the form_validation errors either.
I used the documentation to set it up along with the guides on SO. Will eventually go to Ion Auth but want to know how to fix this. As I am still learning code igniter mvc.
Model
class user_model extends CI_Model{
public function register($encrypt_pass){
$data = array(
'name'=> $this->input->post('name'),
'email'=> $this->input->post('email'),
'username'=> $this->input->post('username'),
'password'=>password_hash($encrypt_pass,PASSWORD_BCRYPT)
);
return $this->db->insert('customers',$data);
}
public function login($username,$password){
//validate the inputs from form
$this->db->where('username',$username);
$query = $this->db->get('customers'); //customers is the table
$result = $query->row_array();
if(!empty($result) && password_verify($password, $result['password'])){
return $result;
}
else{
return "false";
}
}
}
Controller
public function login()
{
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required');
if($this->form_validation->run()=== FALSE){
$this->load->view('templates/header');
$this->load->view('users/login',$data);
$this->load->view('templates/footer');
}
else {
//Getting username
$username = $this->input->post('Username');
//Getting and ecrypting password
$password = $this->input->post('Password');//password hashed
$user_id = $this->user_model->login($result);
//checking for user/pass correct will set session if so
if($user_id){
$this->session->set_flashdata('user_loggedin','You are now logged in');
redirect('posts');
}
// If combo is incorrect will redirect
else{
$this->session->set_flashdata('user_loggedin','Login Failed, Please Try
Again');
redirect('users/login');
}
}
}
}
Here is a simple working login code, there are many ways how to do it, it's just an example.
ON YOUR MODEL
Create a function that will check/get the username's password.
public function _getUserPassword($user_name){
$data = array();
$this->db->select('PASSWORD');
$this->db->from('tbl_user');
$this->db->where('USER_NAME', $user_name);
$query = $this->db->get();
if($query->num_rows() > 0){
foreach($query->result_array() as $field_name => $field_value){
$data = $field_value;
}
return $data;
}
else{
return false;
}
}
I've seen your's just selecting it.
We need to use that _getUserPassword function on we call it verify function
function verify($username, $password){
$data = array();
$userNameExists = $this->_getUserPassword($username);
if(password_verify($password, $userNameExists['PASSWORD'])){
$this->db->select('*');
$this->db->from('tbl_user AS user');
$this->db->where('USER_NAME', $username);
$query = $this->db->get();
if($query->num_rows() > 0){
foreach($query->result_array() as $field_name => $field_value){
$data = $field_value;
}
return $data;
}
else{
return false;
}
}
else{
return false;
}
}
So if the verification is success it will return the data to your controller, Let's use your controller.
Let's assume that you changed the models
ON YOUR CONTROLLER
public function login()
{
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required');
if($this->form_validation->run()=== FALSE){
$this->load->view('templates/header');
$this->load->view('users/login',$data);
$this->load->view('templates/footer');
}else {
//Getting username
$username = $this->input->post('Username');
//Getting and ecrypting password
$password = $this->input->post('Password');
$user_id = $this->user_model->verify($username,$password);
//checking for user/pass correct will set session if so
if($user_id){
$this->session->set_userdata('user_loggedin','You are now logged in');
redirect('posts');
}else{
//DO NOT SET USER DATA SESSION HERE UNLESS IT WILL AUTOMATICALLY LOGGED IN.
redirect('users/login');
}
}
}
Hope this helps!
where you are checking that password is matching or not.
try this in your controller.after user check.
if($user>0){
if (password_verify($this->input->post('Password'), $user_id['password'])) {
//success message
}
else{
//error message.password is invalid
}

change password in codeigniter with logged in users throws error

I want to change the password for logged in users,but it always give me an error:[Message: Trying to get property 'password' of non-object] in the controller. How to solve this error???
Please help,Thanks much!
This is my controller:
if($this->form_validation->run()){
$cur_password = md5($this->input->post('cpassword')); // md5-encrypt the password
$new_password = md5($this->input->post('npassword'));
$conf_password = md5($this->input->post('copassword'));
//$this->load->model('queries');
$this->load->library('session');
$user_id = $this->session->userdata('user_id');//multiple users id login
$passwd = $this->queries->getCurPassword($user_id);
!ERROR FOUND HERE!->if($passwd->password == $cur_password){
if($new_password == $conf_password){
if($this->queries->updatePassword($new_password,$user_id)){
echo 'Password Updated Successfully!';
echo '<br/><label>Back to homepage</label><br/>';
}else{
echo 'Failed To Update Password!!';
}
}else{
echo 'New Password and Confirm Password is not matching!!';
}
}else{
echo 'Sorry! Current Password is not matching!!';
}
}else{
echo validation_errors();
}
This is my model:
<?php
class Queries extends CI_Model{
function login() {
$query = $this->db->select('*')
->from('users')
->where('id');
return $query->row();
}
function index() {
$userid = $this->login()->id; //id of the user which is currently logged IN
$this->session->set_userdata('user_id', $user_id);
}
public function getCurPassword($user_id){
$query = $this->db->where(['id'=>$user_id])
->get('users');
if($query->num_rows() > 0 ){
return $query->row();
}
}
public function updatePassword($new_password,$user_id){
$data = array(
//'password' => md5($this->input->post("$new_password"))
'password' => ($new_password)
//'password'=> password_hash(["$new_password"],PASSWORD_BCRYPT)
);
return $this->db->where('id',$user_id)
->update('users',$data);
}
}
Thanks!
You have error in your syntax error says that you are trying to get property of non-object means $passwd may be an array
if($passwd['password'] == $cur_password)
And in case you have null user_id
Place these two lines in your controller function above if($this->form_validation->run()){ line
$userid = $this->queries->login()->id; //id of the user which is currently logged IN
$this->session->set_userdata('user_id', $userid);
and in your login function in model
function login() {
$query = $this->db->select('*')
->from('users')
->where('username',$this->session->userdata('username'));
return $query->row();
}
Hope it helps!
This happens when the user_id not found.
Notice that the getCurPassword function will return the user if found (when checking if num_rows > 0) but if didn't found it returns NULL.
When this happens the $passwd var is null so you cann't access $passwd->password.
You can solve it by changing the if statement to:
if($passwd && $passwd->password == $cur_password){
Edited Try to retrieve your user name as and then call with it the getCurPassword function:
$user_name = $this->session->userdata('username');
$passwd = $this->queries->getCurPassword($user_name );
And in the controller change getCurPassword function as:
public function getCurPassword($user_name){
$query = $this->db->select('*')
->from('users')
->where('username', $user_name);
if($query->num_rows() > 0 ){
return $query->row();
}
}
Notice that I assume you have "username" column in your DB

Connecting Log-in credentials to retrieved data in codeigniter

I've been encountering problems with passing variables form different views. What i want is whenever a user logs in his id, It would automatically retrieve the data that is connected to that ID from the database.
Apparently, I have 3 controllers for my login (c_home,c_login and c_verifylogin), 1 model (m_login) and 1 view (v_home)
Can anyone tell me what I am missing?
Controllers:
c_login
function index() {
$this->load->helper(array('form','html'));
$this->load->view('v_login'); //load view for login
}
c_home
function index() {
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['studentid'] = $session_data['studentid'];
$this->load->view('v_display', $data);
} else {
//If no session, redirect to login page
redirect('c_login', 'refresh');
}
}
function getGrades() {
$data['query'] = $this->m_login->result_getGrades();
$this->load->view('v_display', $data);
}
function logout() {
//remove all session data
$this->session->unset_userdata('logged_in');
$this->session->sess_destroy();
redirect('c_login', 'refresh');
}
c_verifylogin
function index() {
$this->form_validation->set_rules('studentid', 'studentid', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE) {
$this->load->view('v_login');
} else {
//Go to private area
redirect('c_home', 'refresh');
}
}
function check_database() {
//Field validation succeeded. Validate against database
$studentid = $this->input->post('studentid');
$password = $this->input->post('password');
//query the database
$result = $this->login->login($studentid, $password);
if($result) {
$sess_array = array();
foreach($result as $row) {
//create the session
$sess_array = array('studentid' => $row->studentid);
//set session with value from database
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
} else {
//if form validate false
$this->form_validation->set_message('check_database', 'Invalid username or password');
return FALSE;
}
}
m_login
function login($studentid, $password)
{
//create query to connect user login database
$this->db->select('studentid, password');
$this->db->from('users');
$this->db->where('studentid', $studentid);
$this->db->where('password', md5($password));
$this->db->limit(1);
//get query and processing
$query = $this->db->get();
if($query->num_rows() == 1) {
return $query->result(); //if data is true
} else {
return false; //if data is wrong
}
}
function result_getGrades()
{
$this->db->select('grades.blockcode,subjectblocking.subjectcode,subjects.description,grades.final');
$this->db->from('grades');
$this->db->join('subjectblocking','grades.blockcode=subjectblocking.blockcode');
$this->db->join('subjects','subjectblocking.subjectcode=subjects.subjectcode');
$this->db->where('studentid', '2013-F0218');
$this->db->where('sem', '1');
$this->db->where('sy','2013-2014');
$query=$this->db->get();
return $query->result();
}
Views: v_display
<!DOCTYPE html>
<head>
<title>Simple Login with CodeIgniter - Private Area</title>
</head>
<body>
<h1>Home</h1>
<h2>Welcome <?php echo $studentid; ?>!</h2>
Logout
<table class="table">
<thead>
<th>Subject Code</th>
<th>Description</th>
<th>Grade</th>
</thead>
<?php foreach ($query as $row){ ?>
<tr>
<td><?php echo $row->subjectcode;?><br></td>
<td><?php echo $row->description;?><br></td>
<td><?php echo $row->final;?><br></td>
</tr>
<?php } ?>
</table>
</body>
</html>
and the error that i have encountered is
Message: Undefined variable: query
and
Message: Invalid argument supplied for foreach()
The first thing I see is, that you don't name the table in your query:
Change:
$query = $this->db->get();
To this:
$query = $this->db->get("your_table_name_here);
When I read your code I feel headache.
You can actually just put the verify login in your c_login and not create another c_verify controller.
To make it sense
Try to refactor your code like the connection will be like this
c_home = private page that can only be access if the user is login
c_login = verify if the input of user passed and check the data from database.
To summarize
c_login will compose of this functions :
verify user input
check database through m_login
Note: Your logout should be put in the core so that all controller can use it
In your c_home, you just need to create a model that will get the data from database and pass it to your
$data['grades'] = $your_model->get_grades
the variable grades will now be pass to view using $data.
Note: You don't need to create another function to just get the data. What you only need is the model because that is the purpose of model and just pass it in your variable in your controller.
https://www.codeigniter.com/userguide3/general/
Summarize :
From Model -> Controller -> View Get data from model pass it in
controller show it in view

How to take specific data from table and store it in a cookie codeigniter php?

I'm new to codeigniter and php, few days only, so I need a little help.
I'm trying to put some data in my cookie from table so I can check where to redirect user after login. In table users there are two columns named Admin and Company with one or zero if user is or not, and then i wish to insert that information to cookie.
function conformation in user_controler is:
function conformation(){
$this->load->model('user');
$q = $this->user->confr();
if($q){
$data = array(
'username' => $this->input->post('username'),
'Admin' => $this->input->post($a = $this->user->getAdmin), // get 1/0 from users column Admin
'Company' => $this->input->post($c = $this->user->getComp),
'login' => true
);
if( $a == 1 ){ //is admin redirect to admin view
$this->session->set_userdata($data);
redirect('user_controler/useradm');
}
if($c == 1){ //if company redirect to company view
$this->session->set_userdata($data);
redirect('user_controler/usercomp');
}
$this->session->set_userdata($data);// if common user redirect to user view
redirect('user_controler/userpro');
}
else{ // if nothing above redirect to login page
redirect('user_controler/log');
}
}
And in user model:
function getAdmin{
$this->db->where('Admin', 1);
$a = $this->db->get('users');
}
function getComp{
$this->db->where('Company', 1);
$a = $this->db->get('users');
}
function conf(){
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$q = $this->db->get('users');
if($q->num_rows == 1 ){
return TRUE;
}
}
Also have site controller for checking login
class Site extends CI_Controller{
function __construct() {
parent::__construct();
$this->login();
}
function login(){
$login = $this->session->userdata('login');
if(!isset($login) || login != TRUE){
$this->log;
die();
}
}
}
Of course it's not working because i should probably check these column some other way but I don't know how. I Also have enabled table ci_session and it's work perfectly without Admin and Company.
Hello and welcome to Stackoverflow.
Here are my updates to the code (I have annotated my changes):
function conformation(){
$this->load->model('user');
if($this->user->confr()){ //$q wasn't needed, as you are only using this twice
$user = $this->input->post('username'); //I have added this as I will be referring to it a couple of times.
$data = array(
'username' => $user,
'Admin' => $this->user->getAdmin($user), // Your method was questioning the original form looking for data that it would never find - This will question your model.
'Company' => $this->user->getComp($user), //Same as above
'login' => true
);
$this->session->set_userdata($data); //It doesn't matter who the user is, we shall set the data to start with.
if($this->user->getAdmin($user)){ //is admin redirect to admin view
redirect('user_controler/useradm');
}
elseif($this->user->getComp($user)){ //if company redirect to company view
redirect('user_controler/usercomp');
}
else { //Redirect non-privileged users.
redirect('user_controler/userpro');
}
}
else{ // if nothing above redirect to login page
redirect('user_controler/log');
}
}
Users Model:
function getAdmin($user){
$this->db->where('username', $user); //Before you was just returning everyone who is an admin This instead finds the user
$a = $this->db->get('users');
foreach($a as $u) {
if($u["Admin"]==1) { return true; } //This finds if the user is a admin or not, and the function will now return a value (true)
}
}
function getComp($user) {
$this->db->where('username', $user);
$a = $this->db->get('users');
foreach($a as $u) {
if($u["Company"]==1) { return true; }
}
} //Edited similar to the function above
function conf(){
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$q = $this->db->get('users');
if($q->num_rows == 1 ){
return TRUE;
}
}
Lastly your login function:
function login(){
$login = $this->session->userdata('login');
if(!isset($login) || $login != TRUE){ //You weren't referring to your $login variable
$this->log;
die();
}
}
Hopefully this helps with your problems, let me know if you need any amendments.

Categories