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..
Related
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
I'm currently working on an existing website created in codeigniter.
Whenever a user enters a page, he gets redirected to frontpage.php, that checks if the user is logged in, if not he gets redirected to the login page.
Now, I have one page where this frontpage.php shouldnt be executed, and any user can enter it.
Any help is greatly appreciated.
Had a similar problem and solved it this way by using some online tutorials
1: Make a seperate loginpage (ex login.php) prior to the 'frontpage.php'.
2: Pass the login, password and a session variable to the frontpage.
3: Recode you 'frontpage.php' to check for the session variable passed by 'login.php'.
If u entered the page trough the normal way it will use the normal login.
if u entered the page trough the new 'login.php' page it will be picked up by the recoded 'frontpage.php' and bypass the normal way.
Hope this helps
Grtz
Re-route everything to your pages controller and use this as your default
$route['default_controller'] = 'pages';
$route['(.*)'] = 'pages/index/$1';
-
class Pages extends CI_Controller
{
protected $currentUser = null;
public function __construct()
{
parent::__construct();
$this->currentUser = Auth::getCurrentUserObject(); //check user is logged in
}
public function index($uri='home')
{
$sizeOfSegments = sizeof($this->uri->rsegments);
if ($sizeOfSegments >= 3)
{
$uri = $this->uri->rsegments[3];
}
else
{
$uri = 'home';
}
$pageFound = Page::find($uri); //query the database
if (!$pageFound)
{
return show_404($uri); // find out where there were headed
}
unset($sizeOfSegments, $uri);
if(is_null($this->currentUser) OR !$this->currentUserHasPermissionToViewThisPage OR !$pageIsNotPublic)
{
return redirect('login');
}
$this->load->view();
}
}
make new controller
class Newpage extends CI_Controller {
public function index(){
$this->load->view('newpage');
}
}
now goto
yourhost.com/index.php/newpage
May be your default Controller have a coding of checking whether user is logged or not. Please remove or change the code in controller.
I think you need to delete the controller, it works like that!
How do I change the content for a user when he logs in? I mean like enabling voting, changing "login" to "logout" etc.
What I think to do is to start the session when user logs in (I am preferring to start session only when user logs in, not all the time). Then add data to the session's cookie like-
//controller
$moredata = array(
'username' => $this->username,
'login' => TRUE
);
$this->session->set_userdata($modedata);
//redirect
Then in the other controller, where he has been redirected I check the following-
$login = $this->session->userdata('login');
if ($login==TRUE)
Depending on the 'if' condition I will pass a variable to the view, with the help of that variable I will forward only the div/sections which should be shown to a logged-in user.
The problem is, while performing the above comparison Codeigniter shows following error (remember I haven't added 'session' in autoload array yet)
Message: Undefined property: NameOfController::$session
And If I set following in the autoload file
$autoload['libraries'] = array('session');
then the "if ($login==TRUE)" comparison always shows FALSE.
What should I do?
If I were you, I'd place all your session checks in a base controller which all your other main controllers extend. This allows you to keep things DRY:
class BaseController extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function isLoggedIn()
{
// Will return true or false
return $this->session->userdata('login');
}
}
And in one of your functional controllers (the example below handles users):
class UserController extends BaseController {
public function __construct()
{
parent::__construct();
}
public function profile()
{
// Redirect if not logged in
if (!$this->isLoggedIn()) {
$this->redirect('some/other/page')
}
}
public function register()
{
// Show different HTML if not logged in
$data = array(
'isLoggedIn' => $this->isLoggedIn()
);
$this->load->view('register', $data);
}
}
The second method in UserController allows you to render different content in your view:
<? if ($isLoggedIn): ?>
<p>You're logged in!</p>
<? else: ?>
<p>Not logged in</p>
<? endif; ?>
On my last project we created a simple permissions helper that had functions to check for logged-in status and for privilege levels. Then we'd just call the helper's functions as needed from anywhere in the system. If the user is logged in and has privs for that content then they get the content - otherwise we'd redirect them to a registration or other error page. Since all of that logic is in the helper functions, we could wrap any permission-requiring code in a quick permissions call like if(is_logged_in()){code requiring login to access}.
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');
}
The issue here is that when my user logs into my app, they always are redirected to the default controller.
I would like the user to be redirected to the page they were on before logging in.
So for example, if the user is reading forum post #12 (reading does not require login) and then decides to post an answer (answering requires login), once they login they should go back to post #12.
I am using PHP/Codeigniter 2.0.2 and the Tank_Auth library, and have in several of my controllers
function __construct()
{
parent::__construct();
if (!$this->tank_auth->is_logged_in()) {
redirect('/auth/login/');
} else {
//load stuff
}
My question is
What is the best way to set a return URL (Cookie? GET?), and how would that be implemented?
If you're familiar with Tank_Auth, in which files should I make these changes?
Any roadmaps are welcome, even if you don't use Tank_Auth.
I Recently implemented this solution on a webpage I was working.
In the controller/auth file add a reference to the user_agent library:
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->library('security');
$this->load->library('tank_auth');
$this->lang->load('tank_auth');
$this->load->library('user_agent'); //This is the line you are adding
}
In the views/auth/login_form.php and taking advantage of the CodeIgniter's user_agent library add a hidden input tag which will contain the referrer url as follows:
<?=form_hidden('redirect_url', $this->agent->referrer());?>
<?php echo form_submit('submit', 'Let me in'); ?>
<?php echo form_close(); ?>
After that, all you have to do is redirect the users to the content of the input named "redirect_url" when the user posts the login data to the login action:
/**
* Login user on the site
*
* #return void
*/
function login()
{
/*.... Beginning of the login action function...
....
....
*/
if ($this->tank_auth->login(
$this->form_validation->set_value('login'),
$this->form_validation->set_value('password'),
$this->form_validation->set_value('remember'),
$data['login_by_username'],$data['login_by_email'])) //valid
{
redirect( $this->input->post('redirect_url'));
}
}
This works great for me... It's fine and simple. I believe it can help you.
Let me know about anything.
This is the solution I've been using with tank_auth, it's probably not the best, but I've found it works well for me.
In the controller
if (!$this->tank_auth->is_logged_in()){
$encoded_uri = preg_replace('"/"', '_', $_SERVER['REQUEST_URI']);
redirect('/login/'.$encoded_uri);
}elseif($this->tank_auth->is_logged_in(FALSE)){ // logged in, not activated
redirect('/user/reactivate/');
}else{
//Logged IN Stuff Here
}
Modified Tank Auth Login Function (controllers/auth.php)
function login($return_to = "")
{
if ($this->form_validation->run()) {
if ($this->tank_auth->login(
$this->form_validation->set_value('login'),
$this->form_validation->set_value('password'),
$this->form_validation->set_value('remember'),
$data['login_by_username'],
$data['login_by_email'])) {
//...Other Stuff Here
$decoded_uri = preg_replace('"_"','/',$return_to);
redirect($decoded_uri);
}
}
}
You may need to change the preg_replace to something else if your urls have _ in them, I just used that because it works for me
EDIT
I've updated the function, this is one from another project that we heavily modified the tank auth stuff, so if stuff is a bit different, I'm sorry
As for the passing the encode_uri stuff, I've added the following to the routes.php file (config/routes.php)
$route['auth/login/(:any)'] = 'auth/login/$1';
$route['auth/login'] = 'auth/login'; //Probably don't need this one now
Hi I solved it as follows
In your controller
Add this: $this->load->library(array('tank_auth');
if (!$this->tank_auth->is_logged_in()) {
$encoded_uri = preg_replace('"/"', '_', $this->uri->uri_string());
redirect('/auth/login/'.$encoded_uri);
} else {
// Logged IN Stuff Here
}
In Tank Auth Controller (controllers/auth.php)
function login($return_to = "")
{
if ($this->form_validation->run()) {
if ($this->tank_auth->login(
$this->form_validation->set_value('login'),
$this->form_validation->set_value('password'),
$this->form_validation->set_value('remember'),
$data['login_by_username'],
$data['login_by_email'])) {
// success
$decoded_uri = preg_replace('"_"','/',$return_to);
redirect($decoded_uri);
}
}
}
I replaced $_SERVER['REQUEST_URI'] with this $this->uri->uri_string() because that allow you get /controller/method/...etc. to redirect later in tank auth controller
That work perfect for me and how said #Cubed Eye "You may need to change the preg_replace to something else if your urls have _ in them"
Thanks to #Cubed Eye
I hope this helps someone else too.