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}.
Related
i have a login process where the user can view his dashboard after login.
The code in controller:
$adminid = $this->am->login_admin($email, $password);
if ($adminid) {
$admin_data = array(
'adminid' => $adminid,
'email' => $email,
'logged_in' => true,
'loggedin_time' => time()
);
$this->session->set_userdata($admin_data);
$this->session->set_flashdata('login_success', 'You are logged in');
redirect('Admin_dashboard/dashboard/' . $adminid);
} else {
$this->session->set_flashdata('login_failed', 'Invalid login!!');
redirect('admin/index');
}
After successful login the user is getting redirected to the following url
localhost/project/Admin_dashboard/dashboard/1
The issue is that if the user manually changes the url to something like this-
localhost/project/Admin_dashboard/dashboard/2
he is able to access the data of user whose id is 2 without login
To solve the issue i tried using the following codition in the view
<?php if($this->session->userdata('logged_in')): ?>
<? endif; ?>
However the 2nd url is still accessible
After login the user gets redirected to dashboard that also contains few other pages such as profile page, payment page etc which contains data that is only related to him.
I want that after login he should be able to see all his pages but not anyone else data by changing the url
Simply do one thing, instead of passing $adminid with the url, get the adminid with session, because you also storing values in session.
Instead of
redirect('Admin_dashboard/dashboard/' . $adminid);
Use this
redirect('Admin_dashboard/dashboard');
and inside the dashboard function in Controller use this
public function dashboard (){
$admin_data = $this->session->userdata('admin_data');
if(!isset($admin_data['adminid']) || empty($admin_data['adminid'])){
//Error message Login First
redirect('admin/index');
}
$adminid = $admin_data['adminid'];
//Proceed with this $adminid
}
Simply add this code to all controllers for maintaining user restrictions throughout all URLs.
Class Controller_name extends CI_Controller{
function __construct(){
parent::__construct();
if(!isset($this->session->userdata['logged_in'])){
//redirect login page
}
}
/**
Your Other Functions
**/
}
Let me know If you have anymore doubts..
set user session is valid or not in dashboard controller before load dashboard view and also check user session adminid value with uri segment value
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
function __construct() {
parent::__construct();
if (!$this->session->userdata('logged_in')) {
redirect('Login', 'refresh');
}else{
$uri_admin_val=$this->uri->segment(2);
$adminid=$this->session->userdata('adminid')
if($adminid!=$uri_admin_val){
redirect('Admin_dashboard/dashboard/' . $adminid);
}
}
}
}
And extend this my controller on dashboard and other controller
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Dashboard extends MY_Controller {
public $data;
public function __construct() {
}
}
I have a login script, and when the login is successful I want it to redirect them to the home page(welcome_message.php) for some reason it does not link me to this file, instead throws a 404 and says "The requested URL "http://localhost/musiclear/index.php/views/welcome_message" cannot be found or is not available. Please check the spelling or try again later."
I am using CodeIgniters redirect() function for the change.
function validate_credentials() {
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if ($query) { // if users credentials validated
$data = array('usernames' => $this->input->post('username'),
'is_logged_in' => true);
$this->session->set_userdata($data); //set session data
redirect('welcome_message'); //redirect to home page
} else { //incorrect username or password
$this->index();
}
}
Try passing the full URI to the redirect function like so:
redirect(base_url('views/welcome_message'));
Assuming of course that your controller is Views and page (function) is welcome_message
You can't redirect browser to view file directly, but You can redirect it to controller, which will show Your view. In Your example You're trying to access CodeIgniter's (which based in musiclear folder on Your localhost) Controller with name views and call welcome_message() method from it. But if Your really want to show it You must have next structure:
musiclear/
Application
Controllers
views.php
and views.php content:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Views extends CI_Controller {
function index() {
// default action, required method
}
function welcome_message(){
$this->load->view('welcome_message');
}
}
?>
actually when you make redirects in CodeIgniters it looks up for your controller and you should load view through the function of controller. e.g:
function validate_credentials() {
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if ($query) { // if users credentials validated
$data = array('usernames' => $this->input->post('username'),
'is_logged_in' => true);
$this->session->set_userdata($data); //set session data
redirect(base_url().'home/welcome'); //redirect to home function
} else { //incorrect username or password
$this->index();
}
}
function welcome(){
$this->load->view('welcome_mesage');
}
May be you forgot that redirect() function work only for controller class ie.
let you have welcomeclass so you can redirect it by using
redirect('wolcome');
you also redirect a function of controller class
if you want to redirect to page function of welcome controller class so you will writr
redirect('welcome/page');
I have this controller: Resales, and I am in the Administrator controller and need to create a new Resale.. how should I do that?
first option:
Administrator form calls /resales/addResales
second option: Administrator has a method addResale that loads the Resale model and inserts it.
What should I do?
thanks
Administrator controller shouldn't be loading the Resales controller - that should be a model that both controllers use. You should load your Resales model into the Administrator controller in the $uses = array() property at the top of your controller file:
class AdministratorController extends AppController {
var $uses = array('Resale', //the rest of your models);
public function createResale() {
$this->Resale->create();
$this->Resale->set($this->data['Resale']);
$this->Resale->save();
}
}
Other options are that you could use Ajax to post the request for you, or you could use $this->requestAction() in your Administrator controller to use a processing function in your Resales controller:
// administrator controller
public function createResale() {
// define your data here
$result = $this->requestAction('resales/create', array($data_array));
}
Have a look at the manual for more information on requestAction:
http://book.cakephp.org/2.0/en/controllers.html
EDIT
You've just asked about views. In this case, there's no real need to create a view for createResale(), what you might want to do instead is set a Session flash message, then redirect back to your form. You will need to ensure you've included the Session helper at the top of your controller:
class AdministratorController extends AppController {
var $helpers = array('Session', // any others here);
Then you prevent the layout and render of views, do your thing and set a session flash with the results message:
public function createResale() {
// don't render a view or layout
$this->layout = '';
$this->render(false);
// process your request
$result = // do stuff... return true or false for result
$msg = $result ? 'Added successfully!' : 'Error adding resale!';
// set flash message
$this->Session->setFlash($msg);
// return to that form
$this->redirect(array('action' => 'formYouCameFrom'));
}
Now on your form, you'll simply do this:
echo $this->Session->flash();
... which will output the results.
I am working on codeigniter. I am implementing signin functionality and when user signs in i call this controller
function validate_credentials()
{
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query==1)
{
$data = array
(
'username'=>$this->input->post('username'),
'is_logged_in' => true
);
$email=$data['username'];
$this->session->set_userdata('email_of_user',$email);
$this->load->model('search_peoplee');
$data['userid']= $this->search_peoplee->get_userid_from_email($email);
foreach ($data['userid'] as $row)
{
$one=$row->userid;
}
$data['result']=$this->membership_model->friend_notify($one);
$data['count']=$this->search_peoplee->get_friends_count($one);
$this->load->model('search_peoplee');
$data['values']= $this->search_peoplee->get_notifications($one);
$data['count_notify']=$this->search_peoplee->get_notifications_count($one);
$this->session->set_userdata('lookatit','no');
$this->load->view('home_screen',$data);
}
elseif($query==2)
{
$data['main_content']='email_not_found';
$this->load->view('includes/template',$data);
}
else
{
$this->error_index();
}
}
this validates the credentials and stores a session, this controller calls a model "$this->membership_model->validate();" which picks the value form view and check that if user exists, the problem is when i retype the address it takes me to the login page and says sign in again as the model reads empty values. How to avoid this. help!!!
after you have authenticated, how about setting a session variable.
so,
$this->session->set_userdata('authenticated',TRUE);
then in the controller, first check if the user is authenticated and do a redirect, otherwise go to the validate_credentials method ??
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!