I have been following a tutorial on youtube about CodeIgniter. The tutorial only relies on $username $_SESSION variable and doesn't touch on other aspects of $_SESSIONs. According to code igniter documentation regarding $_SESSION you can simply call the session super global with the key. This is where my problem starts.
VAR_DUMP($_SESSION)
a var_dump of $_Session provides the following info (I have truncated other fields to keep it shorter)
array (size=5)
'__ci_last_regenerate' => int 1526800056
'' => null
'userID' =>
array (size=1)
0 =>
array (size=14)
'userID' => string '1' (length=1)
'firstname' => string 'Tim' (length=3)
'lastname' => string 'Coetzee' (length=7)
'pword' => string 'xyz' (length=4)
'email' => string 'someone#gmail.com' (length=17)
What I want to do
I simply want to be able to call a $_SESSION super global as such $_SESSION['email'] or $_SESSION['userID'] The way I want to access the session vars is EXACTLY as you should do it according to docs, thus I believe my
problem is in my controller() or the way im setting the session data() as can be viewed below
Problem
Lets say I want to display the userID from above var_dump() info in the view just as a test I do the following... echo $_SESSION['userID'];
The above leads to error
Message: Object of class stdClass could not be converted to string
Okay sure enough however what is the object name I should call to get say firstname ?
I tried this as per official docs
echo $this->session->firstname AND echo $this->user_data('userID');
which resulted in same error.
I realize the $_SESSION data seems to be saved in a multi-dimensional array so I tried a foreach() as such
foreach ($_SESSION as $sessions)
{
foreach ($sessions as $value)
{
echo $value;
}
}
which gives me the error:
Message: Invalid argument supplied for foreach()
However after two more similar errors by the last iteration it returns the values of all the sessions, so Im guessing im doing something wrong in the loop.
Code Follows Below
Users_model.php
public function login($username, $password)
{
// Validate
$this->db->where('username', $username);
$this->db->where('pword', $password);
$stmnt = $this->db->get('users');
if($stmnt->num_rows() == 1){
return $stmnt->row(1);
} else {
return false;
}
}
Controller.php
public function login(){
$data['title'] = 'Sign In';
$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 {
// Get username
echo $username = $this->input->post('username');
// Get and encrypt the password
echo $password = $this->input->post('password');
// Login user
$user_id = $this->users_model->login($username, $password);
if($user_id){
// Create session
$user_data = array(
'username' => $username,
'userID' => $user_id,
'logged_in' => true
);
$username = user_data ['username'];
$userID = user_data ['userID'];
$logged_in = user_data ['logged_in'];
$this->session->set_userdata($username );
$this->session->set_userdata($userID );
$this->session->set_userdata($logged_in);
// Set message
//$this->session->set_flashdata('user_loggedin', 'You are now logged in');
redirect('pages/index');
} else {
// Set message
// $this->session->set_flashdata('login_failed', 'Login is invalid');
redirect('users/failed');
}
}
}
$config.php
$autoload['libraries'] = array('form_validation','session', 'pagination');
Any help advice, or constuctive criticism appreciated
Hope this will help you :
if you don't want to change your model query set session like this
$user = $this->users_model->login($username, $password);
if($user)
{
$user_data = array(
'username' => $username,
'userID' => $user->id,
'logged_in' => true
);
$this->session->set_userdata($user_data);
//$this->session->set_flashdata('user_loggedin', 'You are now logged in');
redirect('pages/index');
}
else
{
// Set message
// $this->session->set_flashdata('login_failed', 'Login is invalid');
redirect('users/failed');
}
print individual session key like this :
echo $this->session->userdata('username');
echo $this->session->userdata('userID');
echo $this->session->userdata('logged_in');
and whole session like this :
print_r($this->session->userdata());
Note : for CI Version 3.1.8, access like this :
$username = $this->session->username;
$userid = $this->session->userID;
for more https://www.codeigniter.com/user_guide/libraries/sessions.html#retrieving-session-data
When you echo $_SESSION['userID']; you are trying to display whole array like string, it is immposible.
Also you cannot use two foreach loops because in the first cycle of outer loop there is integer ('__ci_last_regenerate' => int 1526800056) as argument of inner loop, so you get error.
Following your session array structure you can call to fields like that:
echo $_SESSION['userID'][0]['firstname'];
or better:
$name = $this->session->userdata('firstname');
Related
I am having a trouble on displaying my admin's full name, like for example admin full name is John Doe, it is not displaying. I am still learning codeigniter please give me advice thank you!
here is my controller
//Get username
$username = $this->input->post('username');
//Get and encrypt the password
$password = $this->input->post('password');
// Login user
$user_id = $this->role_model->login($username, $password);
if ($user_id) {
// Create session
$user_data = array(
'user_id' => $user_id,
'name' => $user_id->name,
'username' => $username,
'logged_in' => true
);
$this->session->set_userdata($user_data);
//Set message
$this->session->set_flashdata('user_loggedin','You are now logged in');
redirect('pages/index');
here is my View - where I would like to display my full name, as you can see 'name' is the data field I have to display but it is does not show anything, it gives an error that says name is not defined.
<li><a> Welcome, <?php echo $this->session->name ?> </a></li>
Model
public function login($username, $password){
//Validate
$this->db->where('username',$username);
$this->db->where('password',$password);
$result = $this->db->get('users');
if ($result->num_rows() == 1) {
return $result->row(0)->id;
}else{
return false;
}
}
Your method login() returns only id = digit (return $result->row(0)->id;), not object (in controller your get $user_id->name).
Do this, in the model:
if ($result->num_rows() == 1) {
return $result->row(0); // fix
}else{
return false;
}
In the controller:
$user = $this->role_model->login($username, $password);
$user_data = array(
'user_id' => $user->id, // fix
'name' => $user->name, // fix
'username' => $username,
'logged_in' => true
);
It shows undefined because it is indeed undefined.
In your view your're trying to echo the returning value of a function called userdata(), does that function actually exist? Or is $this->session->userdata an array? in which that case, you need to use [ index ] to acces a member within an array. i.e. $this->session->userdata['name'], but also, that member needs to exist first.
controller :
if($this->Login_model->login_valid($email,$password))
{
$sessiondata = array(
'username' => $email
);
$this->session->set_userdata('logged_in', $sessiondata);
redirect('narson');
}
else
{
$this->session->set_flashdata('error',"Invalid Username And password");
redirect('login');
}
model:
public function login_valid($username,$password)
{
$this->db->where('username',$username);
$this->db->where('password',$password);
$query = $this->db->get('admin');
if($query->num_rows() > 0)
{
return true;
}
else
{
return false;
}
}
I have an issue regarding session (userdata/flashdata) on my code.
Modal
public function loginCheck(){
$email = $this->input->post('email');
//encrypt password
$this->load->library("hashing");
$password = $this->hashing->incrypt($this->input->post('password'));
$this->params = array('email' => $email, 'password' => $password);
$user = $this->findById();
if(count($user)>0){
$data = array(
'email' => $user->email,
'isLoggedIn' => 1,
'user_id' => $user->id,
'user_type' => $user->user_type
);
$this->session->set_userdata($data);
return true;
}
return false;
}
And my Controller
public function login(){
$this->load->model('model_users');
//if posted login
$submit = $this->input->post('submit');
if($submit){
$this->load->model('model_users');
$rules = $this->model_users->rules;
$this->form_validation->set_rules($rules);
if($this->form_validation->run() == true){
// user credential from model
if($this->model_users->loginCheck()== true){
redirect("admin/site/index");
} else{
$this->session->set_flashdata('message', 'Oops! Invalid email and/ or password.');
redirect("admin/site/login");
}
}else{
$this->session->set_flashdata('message', 'Oops! Invalid email and/ or password.');
redirect("admin/site/login");
}
}
$this->loadPartialView("admin/login");
}
The session is not being set on CI 3.0. The function set_userdata() is not functioning well.
The manual session initializing is also having trouble.
Please try load Session Library into Controller and Modal before using it.
$this->load->library('session');
i dont think if this is a good answer, but have you call your session in view?
as i know ,
CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared.
it can be found in sesseion documentation
so in your view in div tag or other, its like
<?php echo $this->session->flashdata('message');?>
First you can add library of session.
There are two way of add library.
1) You can add in controller method.
2) autoload in autoload.php file.
Hi guys I have a User controller and User_model model. I want to be able to retrieve and display a logged in users email and phone number from the database to a view after the user is logged in. any idea how I could go about this would be appreciated and if codes could be written to demonstrate I would be very happy.
MODEL
public function login($username, $password){
//validation
$this->db->select('id, email, username');
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->where('status', 1);
$result = $this->db->get('users');
if($result->num_rows() == 1){
return $result->row(0)->id;
} else {
return FALSE;
}
}
public function get_user($username){
$this->db->where('username', $username);
$query = $this->db->get('users');
return $query->result();
}
CONTROLLER:
public function login(){
$data['title'] = '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 {
// fetching user
$username = $this->input->post('username');
//Encrypted password
$password = md5($this->input->post('password'));
//login user
$user_id = $this->user_model->login($username, $password);
if($user_id){
//creating session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => TRUE,
);
$this->session->set_userdata('user_data',$user_data);
// Set message to be sent
$this->session->set_flashdata('user_login', 'Welcome');
redirect('posts');
} else {
// Set message to be sent
$this->session->set_flashdata('login_fail', 'Login Failed');
redirect('users/login');
}
}
}
public function get_user()
{
if($this->session->userdata('logged_in')){
$username = $this->session->userdata('username');
$data['results'] = $this->user_model->get_user($username);
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
}
}
There is basic problem in your Controller
Session Data Problem: In your Controller you storing all array data in CodeIgniter Session:
the 'user_data' would work like array key, and all other array will be assign as keys data;
$this->session->set_userdata('user_data', $user_data);
and you retrieving/checking the session data by using $this->session->userdata('logged_in') and $this->session->userdata('username'), It's wrong my friend. You can get user data session by $this->session->userdata('user_data')['username'] or $this->session->userdata['user_data']['username'] ...
Because the session would be like;
Array
(
[__ci_last_regenerate] => 1499791562
// This is the array key 'user_data' where your array data stores
[user_data] => Array
(
[user_id] => 1
[username] => scott
[email] => scott.dimon#example.com
[phone_number] => 1234567890
[first_name] => Scott
[logged_in] => 1
)
)
So, you have to have use 'user_data' with session to get your data
One thing I would like to share with everyone, Always Read The Docs and manual Carefully. Believe me if you read before the start, your code would be more nicer and cleaner... Ha ha ha ha ha.. ;) :|
When you login if you set the users_id in session you can get the information like
Read manual also
https://www.codeigniter.com/user_guide/database/results.html#result-rows
https://www.codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view
Make sure you autoload session, and database.
Examples ONLY below.
Filename: User_model.php
class User_model extends CI_Model {
public function get_user($id)
{
$this->db->where('user_id', $id);
$user_query = $this->db->get('yourtable');
return $user_query->row_array();
}
}
Filename: Dashboard.php
Controller
<?php
class Dashboard extends CI_Controller {
public function __construct()
{
parent::__construct();
if (!$this->session->userdata('user_id'))
{
redirect('logoutcontroller');
}
$this->load->model('user_model');
}
public function index()
{
$userdata = $this->user_model->get_user($this->session->userdata('user_id'));
/** You can use what you want example
$data['email'] = $userdata['email'];
**/
$data['username'] = $userdata['username'];
$this->load->view('some_view', $data);
}
}
View
<?php echo $username;?>
You can use session to carry the logged in user detail.
This is your model code:
//In your model
$query = $this->db
->select('id,email,phone')
->where(['username' => $username, 'password' => $password])
->where('status','1')
->get('users');
$user_data = $query->row_array();
if (!empty($user_data)) {
return $user_data;
} else {
return FALSE;
}
In side the controller where you get the user data if username & password is correct. Here you can put the user data on session:
//In Side Controller
$user_data = $this->user_model->login($username, $password);
if(isset($user_data) && !empty($user_data)){
// you can directly add the `$user_data` to the session as given billow.
// set user data in session
$this->session->set_userdata('user_data', $user_data);
Now after putting a data on session you can retrive it any where, on any view or in side morel, controller.
//retrive the user data in any view
//To echo in view Inside your view code.
<?php
$session_data = $this->session->userdata('user_data');
$user_email = $session_data['email'];
$user_phone = $session_data['phone'];
$user_id = $session_data['id'];
?>
<?= $user_phone ?> OR <?php echo $user_phone; ?>
<?= $user_email ?> OR <?php echo $user_email; ?>
On Your $this->load->view('users/login', $data); this view. Where the HTML & PHP code placed.
Example:
<html>
// Your View Page
</body>
<?php
$session_data = $this->session->userdata('user_data');
$user_email = $session_data['email'];
$user_phone = $session_data['phone'];
$user_id = $session_data['id'];
?>
<h1> Logged In User Email: <?= $user_email ?> </h1>
<h1> Logged In User Phone: <?= $user_phone ?> </h1>
<body>
</html>
Note: Once You save the user data inside the session then you don't need to pass that data to the view form controller. You just need to echo it where you need that.
You need to load session library first. like
$this->load->library('session');
Then after you can save your data into session like,
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
Then where ever you require at controller you can retrive session data like,
$data['session_data'] = $this->session->all_userdata();
and then pass to your view,
$this->load->view('data', $data);
and then access that data into your view with the key,
<?= $session_data['username']; ?>
I hope it helps,
Does this answer your question?
public function login($username, $password){
$db = $this->db;
//validation
$db->select('id, email, username');
$db->where('username', $username);
$db->where('password', $password);
$db->where('status', 1);
$result = $db->get('users')->row_array();
return empty($result['id']) ? false : $result['id'];
}
With a unique index on username you won't need to check the number of rows as it will be limited to 1.
if($user_id){
//creating session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => TRUE,
);
$this->session->set_userdata($user_data);
// Set message to be sent
$data['session_data'] = $this->session->all_userdata();
$this->session->set_flashdata('user_login', 'Welcome');
$this->load->view('posts', $data);
//redirect('posts');
}
else {
// Set message to be sent
$this->session->set_flashdata('login_fail', 'Login Failed');
redirect('users/login');
}
}
at the view,
<?php print_r($session_data); ?>
if you get your session data into print,
you can display it like,
<?= $session_data['user_id']; ?>
****Modal**
//user login**
function userlogin($data)
{
$condition = "username =" . "'" . $data['username'] . "' AND " . "password =" . "'" . $data['password'] . "' AND " . "status = '1'";
$this->db->select("*");
$this->db->from("user");
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1)
{
return $query->result();
}
else {
return false;
}
}
And in your Controller check
if($this->modal_name->login()==false)
{
//redirect user to login page
}
else
{
$data['details'] = $this->modal_name->login();
$this->load->view("post",$data);
}
View
foreach($details as $detail)
{
echo $detail->id;
echo $detail->username;
}
I have a question, I am trying to create a way in which the user who is logged in can register multiple cards under his name. I understand the concept but just cannot apply it. So need help.
So basically I have 2 tables one for users and another for the cards, which are as shown.
new_users
user_money
So basically i created all this table and most of the information are inserted directly by me for example the orig_id.
So basically what I just want to do is that the user logged in can create multiple cards. Maybe the new_users.id could be equal to user_money.orig_id , but I am not sure how can I make them equal to each other and when a new user registers and enters more cards how can that user id and orig id equal to each other.
This is my controller for login and the controller when user adds a card.
public function login(){
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[4]|max_length[32]');
if ($this->form_validation->run() == FALSE){
$this->load->view('header_view');
$this->load->view('body_view');
$this->load->view('footer_view');
}else{
$email = $this->input->post('email');
$password = $this->input->post('password');
$this->load->model('main_page');
$user_id = $this->main_page->login_user($email, $password);
if($user_id){
$user_data = array(
'user_id' => $user_id,
'email' => $email,
'loggedin' => true
);
$this->session->set_flashdata('loggedin_success','you are loggedin');
redirect('main/Admin');
}else{
redirect('main/login');
}
}
}
And this is the function for the new card getting registered.
public function insertUserCard(){
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('cardname', 'CardName', 'required');
$this->form_validation->set_rules('iban', 'IBAN', 'required');
$this->form_validation->set_rules('cc', 'CC', 'required|max_length[4]');
$this->form_validation->set_rules('amount', 'Amount', 'required');
if ($this->form_validation->run() == FALSE){
$this->load->view('header_view');
$this->load->view('admin_view');
$this->load->view('footer_view');
}else{
$data = array(
'card_type' => $this->input->post('cardname'),
'iban' => $this->input->post('iban'),
'cc' => $this->input->post('cc'),
'amount' => $this->input->post('amount'),
'orig_id' => 52
/*so the orig id here is randomly added by me */
);
$this->load->model('main_page');
$this->main_page->storeCardInfo($data);
redirect('main/Admin');
}
}
And just incase if needed the models for both the table data being inserted.
public function login_user($email , $password){
$this->db->where('email', $email);
$this->db->where('password', $password);
$result = $this->db->get('new_users');
if($result ->num_rows() == 1){
return $result->row(0)->id;
}else{
return false;
}
}
public function storeCardInfo($data){
$insert = $this->db->insert('user_money',$data);
return $insert;
}
So would like if someone could help me on how to get one user have multiple rows in the user_money table.
I am using codeigniter and mysql
Just use the user_id that is stored into $user_data inside of login().
First, to make user_data a session variable so that the whole controller can access it, change the line in login() which declares $user_data as a local variable to assign it to a session variable.
Change:
$user_id = $this->main_page->login_user($email, $password);
if($user_id){
$user_data = array(
...
To:
$user_id = $this->main_page->login_user($email, $password);
if($user_id){
$this->session->set_userdata(array(
...
Then... you can change the line in insertUserCard():
'orig_id' => 52
/*so the orig id here is randomly added by me */
to just use the session:
'orig_id' => $this->session->userdata('user_id');
I think, since you are "new to all this", you should perhaps ensure your MySQL database is setup properly with a Foreign Key Constraint. (and that you understand how that works)
I'm creating a session at login but it's not saving the variables I store inside the session nor is it carrying them across to other pages:
Controller code:
function CheckDatabase($password) //This function is only run when password validation is correct.//
{
$username = $this->input->post('Username'); //Sets the username as a $username.//
$result = $this->User_model->Login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array( //Makes an array of the data to be stored in the session.//
'UserID' => $row->UserID,
'Username' => $row->Username
);
$this->session->set_userdata('logged_in', $sess_array); //Sets $sess_array as the session.//
}
return TRUE;
}
else //Ran if the username or password aren't matched in the CIUsers database. Returns error message.//
{
$this->form_validation->set_message('CheckDatabase', 'Invalid login details.');
return false;
}
}
Index function on the same controller (which should stop a user going back to the login screen but doesn't)
function index() //Default function that is run when this controller is called.//
{
if($this->session->userdata('logged_in'))
{
redirect('Home_controller');
}
else
{
$this->load->helper(array('form'));
$this->load->view('Login_view');
}
}
Code on the home view (which browser is directed to once logged in)
<?php echo $UserID .": ".$Username; ?>
I get this error for displaying the session data:
Message: Undefined variable: Username
Filename: views/Home_view.php
Line Number: 9
To retrieve the session variable, you have to do like this
$username = $this->session->userdata['logged_in']['Username'];
echo $username;
You have to retrieve it from session like this before using:
$user = $this->session->userdata('logged_in');
$Username = $user['Username'];
$UserID = $user['UserID'];
Try like this
$newdata = array(
'user_id' => $rows->id,
'user_name' => $rows->name,
'user_image' => $rows->user_image,
'user_email' => $rows->email,
'logged_in' => TRUE,
'user_type' => $rows->user_type
);
}
$this->session->set_userdata($newdata);
And check in your controller construct for user session
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class User extends CI_Controller {
public function __construct() {
parent::__construct();
//Here we will check for the session value if it is true then the function will run else it will redirect to login page
if ($this->session->userdata('logged_in') == FALSE) {
redirect(site_url('your login page'));
} else {
// if there is session value
redirect(site_url('User/your function name');
}
}
}
?>
For complete explaination read this tutorial
http://w3code.in/2015/10/session-handling-in-codeigniter/
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array( //Makes an array of the data to be stored in the session.//
'UserID' => $row[0]->UserID,
'Username' => $row[0]->Username
);
$this->session->set_userdata('logged_in', $sess_array); //Sets $sess_array as the session.//
}
return TRUE;
}