echo user in view from sessions code igniter - php

I am new in codeigniter. I have implemented a simple login system. I want to print out a username on my view page which is stored in sessions.
here is my controller
class LoginController extends CI_Controller {
function index(){
$new['main_content'] = 'loginView';
$this->load->view('loginTemplate/template', $new);
}
function verifyUser(){
//getting parameters from view
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$this->load->model('loginModel');
$query = $this->loginModel->validate($data);
if ($query){
//if the user c validated
//data variable is created becx we want to put username in session
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('sessionController/dashboard_area');
}
else
{
$this->index();
}
}
function logout()
{
$this->session->sess_destroy();
$this->index();
}
}
?>
sessionController
<?php
class SessionController extends CI_Controller {
function __construct()
{
parent::__construct();
$this->is_logged_in();
}
function dashboard_area(){
$data['main_content'] = 'dashboardView';
$this->load->view('dashboardTemplate/template', $data);
}
function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true)
{
echo 'You don\'t have permission to access this page.';
die();
//$this->load->view('login_form');
}else {
return true;
}
}
}
?>
how can i stored a username in sessions and then print out in a page ... i dont want to save username in every controller
if any one have a better suggestions to implement then please share it to me ..

$username = $this->session->userdata('username');
//Pass it in an array to your view like
$data['username']=$username;
$this->load->view('test',$data);
//Then in you view you can display it as:
echo $username;

controller file
$data = array( 'username' => $result->name, );
view file
<?php echo $this->session->userdata('username')?>

Just store the user name in the userdata (you've already done this!)
$this->session->set_userdata('username') = 'John Doe';
And retrieve it just like that
$username = $this->session->userdata('username');

Related

Display the profile information of a logged in user in Codeigniter?

I want to create a profile view for the user that is currently logged in. I created a session_data array for when you log in that only contains their username. How would I retrieve the other values from the row depending on who is logged in? Do I have to add all that information to the session_data array?
I have the values first_name, last_name, & date_joined that I want to display alongside username.
Login Controller:
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('templates/header');
$this->load->view('login');
$this->load->view('templates/footer');
}
function login_validation()
{
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run())
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$this->load->model('login_model');
if ($this->login_model->can_login($username, $password))
{
$session_data = array(
'username' => $username
);
$this->session->set_userdata($session_data);
redirect('home');
}
else {
$this->session->set_flashdata('error', 'Invalid Username and Password');
redirect('login');
}
}
else {
$this->index();
}
}
function enter()
{
if ($this->session->userdata('username') != '') {
echo "Welcome " . $this->session->userdata('username');
echo 'Logout';
}
else {
redirect('login');
}
}
function logout()
{
$this->session->unset_userdata('username');
redirect('login');
}
}
User View:
<h4><?php echo $_SESSION['username']; ?></h4>
You'll need a method in login_model that retrieves the username info based on the username you send to it.
Something like this:
function get_user($username)
{
$this->db->select(*);
$this->db->from('users');
$this->db->where('username', $username);
$query = $this->db->get();
if ($this->db->affected_rows())
{
return $query->row();
}
}
On the other hand, I recommend you to use an existing authentication library.
Ion Auth is pretty good.
Good luck!

Codeigniter - How to avoid user entering logged page without login?

I have Controller called login.php that will take login credentials, if true user will be directed to a method profile() in another controller called page.php.
In that profile() method only contain a command to load the view of user's profile.
So the route is like this:
Home->login->profie
But when I try to bypass the login process via url like this
Home->profile
The system still accept that. How can I make a rule that a user can't open profile if they're not logged in?
Here's the Controller:
page.php
class page extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('User_model', 'user_model', TRUE);
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->status = $this->config->item('status');
$this->roles = $this->config->item('roles');
}
function index() {
$this->load->view('page_header');
$this->load->view('content_front');
$this->load->view('page_footer');
}
function login() {
$this->load->view('page_header');
$this->load->view('content_login');
$this->load->view('page_footer');
}
function register() {
$this->load->view('page_header');
$this->load->view('content_register');
$this->load->view('page_footer');
}
function profile(){
$this->load->view('page_header');
$this->load->view('content_profile');
$this->load->view('page_footer');
}
function success() {
$this->load->view('page_header');
$this->load->view('content_success');
$this->load->view('page_footer');
}
function logout()
{
//destroy session
$data = array('login' => '', 'uname' => '', 'uid' => '');
$this->session->unset_userdata($data);
$this->session->sess_destroy();
redirect('page/index');
}
}
?>
login.php
<?php
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url','html','security'));
$this->load->library(array('session','form_validation'));
$this->load->database();
$this->load->model('user_model');
}
function index()
{
//get form input
$username = $this->input->post('username');
$password = $this->input->post('password');
//form validation
$this->form_validation->set_rules('username','username','trim|required|xss_clean');
$this->form_validation->set_rules('password','Password','trim|required|xss_clean');
if($this->form_validation->run() == FALSE)
{
//validation fail
$this->load->view('content_login');
}
else
{
//check user credentials
$uresult = $this->user_model->get_user($username, $password);
if(count($uresult)>0)
{
//set session
$sess_data = array('login' => TRUE, 'uname' => $uresult[0]->username,'uid' => $uresult[0]->id);
$this->session->set_userdata($sess_data);
$this->load->library('../controllers/page');
$this->page->profile();
}
else
{
$this->session->set_flashdata('msg','<div class = "alert alert-danger text-center">Wrong Email/Password</div>');
$this->load->library('../controllers/page');
$this->page->login();
}
}
}
}
?>
Can anyone please help me how to fix this?
Thank you.
Add a constructor to every applicable controller.
Let the constructor check if the user is logged in, possibly by checking if a particular session exists. If it doesn't redirect to the login page.
Something like below
function __construct(){
parent::__construct();
if(!$this->session->userdata('userid')){
redirect('user/login');
}
}
use this at the top of the page you don't want it accessed when not logged in (supposing you've already set session data)
<?php if (!isset($_SESSION['username'])) {
redirect(base_url());
} ?>
Before showing that page, you should check whether that session exist or not, like if($this->session->userdata('username')). If exists, show that page, if not show any warning.
You can try
if ($this->session->userdata('login') == true) {
redirect('controller');
}
Login Controller
<?php
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url','html','security'));
$this->load->library(array('session','form_validation'));
$this->load->database();
$this->load->model('user_model');
}
function index()
{
if ($this->session->userdata('login') == true) {
redirect('controller');
}
//get form input
$username = $this->input->post('username');
$password = $this->input->post('password');
//form validation
$this->form_validation->set_rules('username','username','trim|required|xss_clean');
$this->form_validation->set_rules('password','Password','trim|required|xss_clean');
if($this->form_validation->run() == FALSE)
{
//validation fail
$this->load->view('content_login');
}
else
{
//check user credentials
$uresult = $this->user_model->get_user($username, $password);
if(count($uresult)>0)
{
//set session
$sess_data = array('login' => TRUE, 'uname' => $uresult[0]->username,'uid' => $uresult[0]->id);
$this->session->set_userdata($sess_data);
$this->load->library('../controllers/page');
$this->page->profile();
}
else
{
$this->session->set_flashdata('msg','<div class = "alert alert-danger text-center">Wrong Email/Password</div>');
$this->load->library('../controllers/page');
$this->page->login();
}
}
}
}
Couple things I noticed also in Codeigniter 3 + versions the first letter must only be upper case on FILENAME and Controller Class
Also you don't need to close the controllers and model with ?> https://www.codeigniter.com/user_guide/general/styleguide.html#php-closing-tag
If for example you don't want the user to enter a function without login, you could check the session in the constructor of the class.
If it's only for a specific function, you could just also check the session in the function directly.
Create a helper file login_helper.php
function check_login( $session ) {
$CI =& get_instance();
$CI->load->helper('url');
if(!$session->userdata('login')){
redirect(base_url());
}
}
Now use this helper function in controllers where login is mandatory
class page extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('User_model', 'user_model', TRUE);
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->status = $this->config->item('status');
$this->roles = $this->config->item('roles');
}
function index() {
$this->load->view('page_header');
$this->load->view('content_front');
$this->load->view('page_footer');
}
function login() {
$this->load->view('page_header');
$this->load->view('content_login');
$this->load->view('page_footer');
}
function register() {
$this->load->view('page_header');
$this->load->view('content_register');
$this->load->view('page_footer');
}
function profile(){
check_login();
$this->load->view('page_header');
$this->load->view('content_profile');
$this->load->view('page_footer');
}
function success() {
$this->load->view('page_header');
$this->load->view('content_success');
$this->load->view('page_footer');
}
function logout()
{
//destroy session
$data = array('login' => '', 'uname' => '', 'uid' => '');
$this->session->unset_userdata($data);
$this->session->sess_destroy();
redirect('page/index');
}
}
?>
Note: add login_helper in autoload.php in config folder.
$autoload['helper'] = array('login','url','cookie');
if($this->session->userdata('logged_in') == FALSE) {
$this->session->set_flashdata('error','<p class="alert alert-danger">Please login to view this page.</p>');
redirect('login_c');
exit;
}

If I already logged in then redirect dashboard page using codeigniter

Login Controller:
class Login extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->library('form_validation');
$this->load->model('login_model');
}
public function index() {
$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('admin/login');
} else {
$result = $this->login_model->select_login($_POST); //check username and password
if ($result) {
$user = array(
'id' => $result['id'],
'username' => $result['username'],
'password' => $result['password']
);
$this->session->set_userdata($user);
redirect('admin/Dashboard');
} else {
$data['msg'] = 'Invalid UserName and Password';
$this->load->view('admin/login', $data);
}
}
}
}
Dashboard Controller:
class Dashboard extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('session');
}
public function index() {
$session_id = $this->session->userdata('id');
if (!empty($session_id)) {
$data = array(
'page_title' => 'Dashboard',
'page_name' => 'dashboard/dashboard',
'admin_username' => $this->session->userdata('username')
);
$this->load->view('admin/template', $data);
} else {
redirect('admin/Login');
}
}
}
Dashboard View:
<html>
<body>
<h1>Helllo Admin</h1>
</body>
</html>
Question
How can I redirect my Dashboard if I'm already logged in?
what is admin in "redirect('admin/Dashboard');". Did you made any changes to url in route file?
When you do this
if ($result) {
$user = array(
'id' => $result['id'],
'username' => $result['username'],
'password' => $result['password']
);
$this->session->set_userdata($user);
redirect('admin/Dashboard');
You are setting your password in your session cookie. All you really need to do is set your username.
You should also do something like this in Login function index()
if(result){
$user = array(
'name' => $result['username]',
'is_logged_in' => TRUE //add this to your session data
);
$this->session->set_userdata($user);
}
Then create a method in whatever controller you are using
public function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if (!isset($is_logged_in) || $is_logged_in != true)
{
redirect("admin/Login");
}
}
When you are in your Dashboard you can use $this->is_logged_in(); to make sure no one else gets into your Dashboard or forms. Use it at the top of your methods for forms or just getting into your dashboard
Then use something like this on your pages
if($this->session->userdata('username') == true){
echo "Hello " . $this->session->userdata('username'). nbs(3), anchor("admin/Dashboard", " Go To Dashboard "); //this is all you need to get to your Dashboard if you are logged in.
}else {
echo " "; //doesnt show up if not logged in
}?>
That acts as a link on your pages that only shows up if you are logged in. At the top of all your Dashboard controller methods add the $is_logged_in();

how to use codeigniter library for login log out

I have created library in codeigniter library and it's named account. I want to get all session data when I call this library, how can I do that. I tried this:
if ($this->account->isLoggedIn()){
$this->ci->session->userdata('isLoggedIn');
}
First Include the Library:
$this->load->library('session');
Store the data in array which you want to store in session :
$data= array(
'username' => 'username',
'password' => 'password',
'email'=>'emailid'
'logged_in' => 'login id'
);
Store this data in session:
$this->session->set_userdata($data);
You can use this data any time for example if you want loginid from session you can write:
$loginid= $this->session->userdata('logged_in');
When Logout:
$this->session->unset_userdata(array("username"=>"","logged_in"=>"","password"=>"","email"=>""));
$this->session->sess_destroy();
redirect('loginpage');
If you don't want to direct access the pages create one model and add this code in it and auto load that model.
public function valid_allowed()//check user is login or not
{
$session = $this->session->userdata('username'); //here you can take loginid, email whatever you store in session
if(!$session)
{
redirect('login');
}
}
To auto load that model
Go to application->config->autoload.php: this line:
$autoload['model'] = array('model name');
Change your model:
class LoginModel extends CI_model
{
public function login($name, $pass)
{
$this->db->select('name,pass');
$this->db->from('members');
$this->db->where('name',$name);
$this->db->where('pass',$pass);
$query = $this->db->get();
if($query->num_rows() == 1)
{
$row=$query->row();
$data=array(
'username'=>$row->u_username,
'id'=>$row->id,
'email'=>$row->email
'password'=>$row->u_password);
$this->session->set_userdata($data);
return true;
}
else
{
return false;
}
}
}
Change your verifyUser function:
public function verifyUser()
{
$name = $this->input->post('username');
$pass = $this->input->post('password');
$this->load->model('LoginModel');
$result=$this->LoginModel->login($name, $pass))
if(!$result)
{
$this->form_validation->set_message('verifyUser','Incorrect Email or Pass');
return false;
redirect('LoginController/checklogin');
}
else
{
redirect('dashboard'); //user is valid so goto dashboard
}
}

Cannot get it correct when is use Session in codeigniter

I have set a session in one method and I want to check in another method, if the user session then user can redirect.
public function validate_credentials(){ //function for validation of users_credentials
$this->load->helper('url');
$this->load->library('form_validation');
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query) //if credential validated
{
$data1 = array(
'username' => $this->input->post('username'),
'is_logged_in' => true );
$this->session->set_userdata($data1);
redirect('site/members_area');
}
else{
$this->home();
}
}}
and i want to be able to use session in a different method below
function get_student(){
$is_logged_in = $this->session->set_userdata('is_logged_in');
if(isset($is_logged_in)){
$studentID = $this->input->get('var1');
$this->load_view($studentID);
$this->load->model('fetch_student'); //model for fetching student profile data
$data['student_prof'] = $this->fetch_student->get_profile($studentID);
$data['main_content']='student/student_profile';
$this->load->view('includes/template',$data);
}
else{
$this->_404();
}
}
You should set and get session like this
In method 1
$this->session->set_userdata('is_logged_in','TRUE');
In method 2
$user = $this->session->userdata('is_logged_in');
if($user != "")
{
//your code goes here
}
Have your load session library in application/config/autoload.php ??
$autoload['libraries'] = array('session');
Actually, I didn't understood what want to write in get_student function but i think this is the way you want.
function get_student(){
$is_logged_in = $this->session->userdata('is_logged_in');
if($is_logged_in != ''){
//your code goes here
}
}
public function validate_credentials(){ //function for validation of users_credentials
$this->load->helper('url');
$this->load->library('form_validation');
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query) //if credential validated
{
$data1 = array(
'username' => $this->input->post('username'),
'is_logged_in' => TRUE );
$this->session->set_userdata($data1);
redirect('site/members_area');
}
else{
$this->home();
}
}}
New Function will be:
public function members_area(){
if($this->session->userdata('is_logged_in')){
///Your coding will be her
}
else{
redirect('controller/login');
}
}
function logout(){
$this->session->unset_userdata('is_logged_in');
redirect('controller/login');
}

Categories