Codeigniter 3 Session Data On Other Pages While User Logged In - php

Got this question here (sorry for being stupid), Just started with Codeigniter recently.
I have a login-system working fine. I tried to go to homepage while logged in with code on index-header.php:
<?php
if( !isset($_SESSION) ){
echo 'Login';
} else {
echo 'Log Out';
}
?>
And on main_view.php (homepage controller)
public function __construct() {
parent::__construct();
$this->load->library('session');
}
public function index() {
if($this->session->userdata('is_logged_in')){
$data['title'] = "Home";
$this->load->view('headfoot/header-main',$data);
$this->load->view('main_view');
$this->load->view('headfoot/footer-main');
} else {
$data['title'] = "Home";
$this->load->view('headfoot/header-main',$data);
$this->load->view('main_view');
$this->load->view('headfoot/footer-main');
}
}
}
Now, if I click logout from homepage while still logged in, it disconnects the session fine but doesn't change text back to "Login" in homepage after refresh.
In other words, it always shows text as "Logout" whether or not user is logged in.
dashboard.php (controller)
public function logout() {
$this->session->sess_destroy();
$data['title'] = "Logged out";
$data['logout_msg'] = "You have successfully logged out.";
$this->load->view('headfoot/header-login',$data);
$this->load->view('admin/login', $data);
$this->load->view('headfoot/footer-login');
}
Is it a good practice to create is_logged_in.php a separate file? If yes then how to link sessions to it?

change this:
<?php
if( !isset($_SESSION) ){
to:
<?php if($this->session->userdata('username') == null ){
i'm using 'username' here by assuming you have set username as session data when you allow user to log in.

Use $this->session->sess_destroy(); to kill session. Check this URL. Kill session by controller then use redirect.
By the way, create a file under application/core folder called MY_Controller.php and make your session things on it. If you want to learn more just google it.

Related

How to prevent user to access login page when its already logged in?

I want to prevent user to access login page when its already logged in. In header page I've checked session so that user can't access any admin page without logging in. What code do I have to write in header page and session page to prevent user access login page while already logged in?
Here's my session class
public static function init(){
session_start();
}
public static function set($key, $val){
$_SESSION[$key]=$val;
}
public static function get($key){
if (isset($_SESSION[$key])) {
return $_SESSION[$key];
} else {
return false;
}
}
public static function checkSession(){
self::init();
if (self::get("login")==false) {
self::destroy();
header("Location:login.php");
}
}
public static function destroy(){
session_destroy();
Check the session variable value on login page if exist then redirect or dashboard or home page if not exist session variable value redirect on login page.
Write your login page like this:
<?php
session_start();
if(isset($_SESSION['key'])){
header('home.php');
} else {
//Paste login page code here
}
?>
And this code avoid the user back to the page after log out
if(!isset($_SESSION['login_user'])){
header("location:login.php");
location.reload();
}
This code is to avoid repeated login from the user
if(isset($_SESSION['login_account_id'])){
header('location: /index.php');
}
<?php
// Initialize the session
session_start();
// If user is already logged in, redirect to index
if($_SESSION["loggedin"] == true){
header("location: index.php");
}
?>

codeigniter - back button after logout still working

created a simple page of session, Even after logout from the page i'm still able to access the login page.
I have also destroyed all the session but still can't find any solution.
view - flashdata_home.php
<form action='add' method='post'>
<input type ='text' name='value'/>
<input type='submit' value='Enter ' />
</form>
Controller - FlashData_Controller.php
<?php
class FlashData_Controller Extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->helper('url');
}
public function index(){
$this->load->view('flashdata_home');
}
public function add(){
// adding flash data
//$this->session->set_flashdata('item','This is me');
$this->session->set_userdata('Name',$this->input->post('value'));
//redirect to home page
// redirect('flashdata');
if($this->session->has_userdata('Name')){
$data = array('value' => $this->session->Name);
$this->load->view('adminflashdata_home',$data);
}
else
{
$this->load->view('flashdata_home');
}
}
public function logout(){
$this->session->unset_userdata('Name');
$this->session->sess_destroy('Name');
$this->load->view('flashdata_home');
}
}
view - adminflashdata_home.php
<?php
echo $value;
<li>Logout</li>
?>
Unsettling the session in CI is very simple and it looks like this.
In your Code you have unset the data but you have to unset the variable as i did.
For Single Data:
$this->session->unset_userdata('some_name');
For Array of Datas:
$array_items = array('username' => '', 'email' => '');
$this->session->unset_userdata($array_items);
For destroy the session:
$this->session->sess_destroy();
I think your problem is, though we destroy session we can still access the page that should be loaded only if the user in logged in.
For example, when user log in with correct credentials the url should look like this: localhost/app/controller/function (just for instance). And later when the user log out you will redirect back to login page. But if we type localhost/app/controller/function in url or if we click back button in browser, the browser will load the page !!! I consider your stated problem is same like this.
For this problem I always use a solution in every function of controller. Like;
class MainController extends CI_Controller {
function test {
$user_name = $this->session->userdata('user_name');
if(isset($user_name)) {
//the actual function code goes here
}
else {
//redirect to the login function
}
}
}
I hope this helped some one.. cheers..

codeigniter: base_url part won't redirect to my controller

I am trying to make a log in work. I am all good with the verification but is stuck when it redirects to an another controller to show the view of the logged in page. I am still new to codeigniter and is still not sure about how controllers work.
This is my controller for verifying logged in users:
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(base_url('c_home'), 'refresh');
}
}
Its function is to validates the user if its in the database, however when the user is successfully logged in, it won't redirect to this redirect(base_url('c_home'), 'refresh'); It tells me that
Object not found!
The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.
If you think this is a server error, please contact the webmaster.
This is the c_home.php where it is supposed to be redirected:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class C_home extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('m_login','',TRUE);
$this->load->helper('url');
$this->load->library(array('form_validation','session'));
}
function index() {
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['studentid'] = $session_data['studentid'];
$this->load->view('v_home', $data);
} else {
//If no session, redirect to login page
redirect('c_login', 'refresh');
}
}
function logout() {
//remove all session data
$this->session->unset_userdata('logged_in');
$this->session->sess_destroy();
redirect(base_url('c_login'), 'refresh');
}
}
is it okay to redirect a controller from another controller?
after it redicts to c_home.php
it will show the v_home.php
<!DOCTYPE html>
<head>
<title>Simple Login with CodeIgniter - Private Area</title>
</head>
<body>
<h1>Home</h1>
<h2>Welcome <?php echo $studentid; ?>!</h2>
Logout
</body>
</html>
You don't need the base_url() in the redirect. just use
redirect('c_home',refresh);
Although there are 2 things i should make you aware of, you need ('controller/function') not just ('controller'). And also make sure you're loading $this->load->helper('url') in your __construct function on both controllers.
Although just for future reference, i think this is what you meant.
redirect(base_url().'c_home',refresh)
Codeigniter's redirect function already has the site_url() embedded.
So, instead of this;
redirect(base_url('c_login'), 'refresh');
Use this, as you have earlier in your code
redirect('c_login', 'refresh');
Hope this helps

Page refresh (F5) always causing form to submit

a bit new to CI, googled and overflowed alot and still got no answer
User enters site.
After succesful auth got redirected to main page
Link on the url stays the same with class/method
If u refresh page on a main - u always got question about repopulate form (chrome/firefox 100%)
the solution may be: after success redirect to another class or method
but i don't know how to do it, documentation seems more like reference to me
code is here: http://paste.ubuntu.com/696751/ line 28 - how to do redirect to another class or method with a redirection to another view too?
Well an example in CodeIgniter may be:
class login extends CI_Controller
{
function index ()
{
$this->load->library('form_validation');
$this->load->helper('url');
//Set form validation rules here: http://codeigniter.com/user_guide/libraries/form_validation.html
if ($this->form_validation->run() == TRUE)
{
//login user here
redirect('login/sucLogin'); // or just redirect to '/' if you want to send them to your home page
}
else
$this->load->view('loginForm'); //make form
}
function sucLogin ()
{
echo 'Successfully logged in';
echo anchor('/', 'Go Home');
}
}
Check to see if the user submitted the form
Validate the login credentials
Redirect on success
public function login()
{
if ($_POST)
{
$login = $this->input->post('login');
$password = md5($this->input->post('password'));
$q = $this->db
->where('login', $login)
->where('password', $password)
->limit(1)
->get('userbase');
if ($q->num_rows > 0 )
{
redirect('enter/main');
}
}
$returnlogin['login'] = $login;
$this->load->helpers('form');
$this->load->view('login_form',$returnlogin);
}
public function main()
{
$this->load->view('main');
}

If isset $_SESSION goto this page?

Ok, having trouble here:
I created a login script, so after a person logs in then they will get direted to another page. And also, I have it redirecting them to the login page if they try and access one of those other pages.
My problem is, if a user is logged in and stumbles to the login page again --by accident-- I would like for it to recognize that the user is logged in and redirect them to that next page (which is index2.php) ?? Having troubles :-(
Here is my code so far:
require_once "inc/functions.class.php";
$quickprotect = new functions('inc/ini.php');
if (isset($_SESSION['goAfterLogin'])){
$goto = $_SESSION['goAfterLogin'];
unset($_SESSION['goAfterLogin']);
}
else $goto = $quickprotect->settings['DEFAULT_LOGIN_SUCCESS_PAGE'];
if (isset($_POST[username])) {
if($quickprotect->login($_POST[username], $_POST[password])) header ("Location: $goto");
}
Here is how I store a users session in the functions page
public function is_logged_in() {
//Determines if a user is logged in or not. Returns true or false;
if ($_SESSION['logged_in'] === md5($this->settings[ADMIN_PW])) {
return true;
}
else return false;
}
You don't mention how you store your users in your session, but something like this should do it for you:
if(isset($_SESSION['user']))
{
header("Location: index2.php");
exit;
}
This will check if you have a user in your session, and if so, redirect to index2.php.
You need to change 'user' according to your session key.

Categories