I have created a simple login in codeigniter, where user enter his/her username and password and if valid then go to some protected page. Protected page has a link called logout. But the problem is after logout if i directly access to protected page it does not redirect to login page.
my protected page contain
<?php
if (!isset($this->session->userdata['loggedin'])) {
redirect("login");
}
?>
Welcome Dear!!
Logout
I have set the session data after successful user credential.
//set the session variables
$sessiondata = array(
'username' => $username,
'loggedin' => TRUE
);
$this->session->set_userdata($sessiondata);
redirect('admin');
In logout method (login is my controller) I have unset the session data like this-
// Removing session data
$sess_array = array(
'username' => '',
'loggedin' => FALSE
);
$this->session->unset_userdata($sess_array);
But after logout when I access directly to admin page(protected) it does not redirect to login page.
After logout I debugged with this on login page, and it shows the already stored session value.
echo $this->session->userdata['username'];
but when i use on logout method it works fine.
$this->session->sess_destroy();
Can anyone tell me why this is happended? Does unset_userdata not working properly or I have done something wrong? Thanks in advanced.
Ok i solve this problem. The problem is codeigniter does not accept array of pairs when unset session data. i.e
I used this code on my application-
// Removing session data
$sess_array = array(
'username' => '',
'loggedin' => FALSE
);
$this->session->unset_userdata($sess_array);
But codeigniter does not support this now. I altered this code with this below code
// Removing session data
$sess_array = array('username','loggedin');
$this->session->unset_userdata($sess_array);
Now it works fine.
Ref- https://www.codeigniter.com/user_guide/libraries/sessions.html
**In previous versions, the unset_userdata() method used to accept an associative array of key => 'dummy value' pairs. This is no longer supported.**
There issue in handling the session in codeigniter
functionality:
$sess_array = $this->session->all_userdata();
foreach ($sess_array as $key => $val) {
if ($key != 'session_id' && $key != 'last_activity' && $key != 'ip_address' && $key != 'user_agent')
$this->session->unset_userdata($key);
}
Above answer Ashis Biswas is fine and you also need to take care that you should check your login session in your controller as in codeigniter you are accessing your controller function instead of view. if you will check and redirect on view page that will not redirect to your login controller even if you have unset session data.
Related
how can i supposed to do that? i think i miss some queries . I hope you guys can help me with this. How to prevent user from going back to the login-page after successful login using back button . Because when I login in and pressed back im going back to my login page. Need help everyone. im using laravel framework
public function login(Request $req)
{
$username=$req->input('email');
$password=$req->input('password');
$breadcrumb = 'Dashboard';
$pageTitle = 'CollabUX | Dashboard';
$prepath ='../';
$currentURL = Req::url();
$user = DB::table('add_users')->where(['username'=>$username,'password'=>$password])->get();
if(count($user)>0){
// Store a piece of data in the session...
session(['isloggedin' => 'true']);
return View::make('dashboard')->with(
array('breadcrumb' => $breadcrumb,'pageTitle' => $pageTitle,'currentURL' => $currentURL,'prepath' => $prepath));
}
else{
//imbes na empty page, redirect ka ulit sa login page
$data = array(
'error' => 1,
'remarks' => 'Invalid Username/Password. Please try again.'
);
return View::make('login')->with('data', $data);
}
}
You can do this by using session_start()
On the start of your home page add this line
session_start()
now on you login page do the following
if(isset($_SESSION['user'])){
// redirect user to $_SERVER['HTTP_REFERER']
}
and in your login function after successful login do this
$_SESSION['user'] = //<user name of logged in user>
on logout do this
session_destroy()
$_SESSION array can hold any number of user defined values, you can use this to store all the data related to a session
$_SERVER['HTTP_REFERER'] will take user to the last url, you might want to change it according to your requirements
Simply do check your login session on login form page, if it is true then redirect them to their dashboard.
I am using PhpMyAdmin and a custom single-sign on (SSO) script for direct login into the interface. The SSO script is called by PHP, given a unique login token by my own system. This script looks up the unique id in my system in order to retrieve MySQL username and password and returns this back to PhpMyAdmin.
This is working so far, but my next goal is automatic logout after a certain amount of inactivity. Without SSO, deleting my browser cookies and clicking any link, I get to the login page with the message »Your session has expired. Please log in again.«. However, I'm not able to reproduce this behavior from within my SSO script.
This is my SSO script:
<?php
/**
* Session timeout in seconds.
*/
define('SESSION_TIMEOUT', 60);
/**
* #return array|null Returns an array with login credentials or null for no login.
*/
function get_login_credentials() {
parse_str($_SERVER['QUERY_STRING'], $query);
/* check for session activity (timeout) */
if (isset($_SESSION['ssoLastActivity']) && (time() - $_SESSION['ssoLastActivity']) > SESSION_TIMEOUT) {
$sessionExpired = true;
} else {
$sessionExpired = false;
}
if (isset($query['old_usr'])) {
/* logout and back to index page */
unset($_SESSION['ssoLastActivity']);
unset($_SESSION['ssoUser']);
unset($_SESSION['ssoPassword']);
header('Location: index.php');
exit;
}
if ($sessionExpired) {
unset($_SESSION['ssoLastActivity']);
unset($_SESSION['ssoUser']);
unset($_SESSION['ssoPassword']);
/******** POINT OF QUESTION ********/
/* I'm trying to give the same response as if the cookies were deleted.
I land on the login page as desired, however I'm missing the session
timeout message. */
header('Content-Type: application/json');
echo json_encode(['redirect_flag' => '1', 'success' => false, 'error' => '']);
exit;
/***********************************/
}
/* update session activity timestamp */
$_SESSION['ssoLastActivity'] = time();
if (!empty($_SESSION['ssoUser']) && !empty($_SESSION['ssoPassword'])) {
/* already logged in */
return [
$_SESSION['ssoUser'],
$_SESSION['ssoPassword'],
];
}
/* retrieve MySQL login credentials here and store them in $user and $password */
/* $user = ...; $password = ...; */
return [
$user,
$password,
];
}
Has anybody a solution for logout via my SSO script, that leads me to the login page with the message, that the session is expired?
UPDATE:
The issue seems to be connected to my PhpMyAdmin server configuration (/etc/phpMyAdmin/servers.ini.php in my case):
<?php
$cfg['Servers'] = array(
1 => array('auth_type' => 'signon', ..., 'SignonScript' => '/usr/share/phpMyAdmin/sso.php', 'SignonURL' => 'index.php?server=1'),
2 => array('auth_type' => 'cookie', ...)
);
I inspected the network request after my session timeout, and it turns out, that there's actually a request with ?session_expired=1 (which triggers the session timeout message) sent to server 1; because this script is returning null (no login), it redirects to the SignonURL index.php?server=1, omitting the extra session_expired query param.
I could extend this url by &session_expired=1, however this would also trigger the message on regular logout.
I'm open for any ideas to improve the behavior.
I have API login using session, when mobile apps use login feature actually they hit the API. In API login, i made session login so when the user login it give response session. check my code below:
public function user_post()
{
$data = array (
'username' => $this->input->get_post('username'),
'password' => sha1($this->input->get_post('password'))
);
$result = $this->login_m->user_check($data);
if ($result ) {
foreach ($result as $row ) {
$sess_array = array(
'username' => $row->username,
'email' => $row->email
);
$this->session->set_userdata('logged', $sess_array);
$this->response(array('success' => $this->session->userdata('logged') ));
}
} else {
$this->response(array(404 => 'missing parameter'));
}
}
and the response will be like this below:
* {
* "success":
* {
* "username": "johndoe123",
* "email": "myemail#my.com"
* }
* }
my question is, how to get the session to validate API post? example:
i have post API to store new data. i've imagine this way would be good, set the param to catch the session name 'logged' using codeigniter , in session 'logged' is already has email and username, so will use it as condition to check to table is the email and username is in the table.
$this->session->has_userdata('logged')
so the mobile apps need to save the session in their apps to send again as params. and the code would be like this below:
$data = array(
'idcardno' => $this->input->get_post('idcardno'),
'dateofbirth' => $this->input->get_post('dateofbirth')
);
$addnewpolis = $this->modelname->modelmethod($data2);
thank you guys,
CMIIW
You cannot use sessions like you want in your code with external api calls. You may generate a token from the login and return it. Then on next api calls from your mobile, send this token in order to know the user identity.
Why: Is it good to implement REST api using Sessions?
To generate a token:
https://www.google.com/search?q=generate%20token%20php&rct=j
Then return it in your response and save it somewhere in order to retrieve it on next calls.
In the login action I'm having the following code:
public function login($sEmail, $sEncryptedPassword, $bIsClear = true)
{
$manager = $this->getServiceLocator()->get('session_manager');
$manager->start();
Container::setDefaultManager($manager);
$this->auth = new AuthenticationService();
$this->auth->setStorage(new Session('FSP'));
$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$this->authAdapter = new AuthAdapter(
$dbAdapter,
'fsp_user',
'email',
'password'
);
$this->authAdapter
->setIdentity($sEmail)
->setCredential($sEncryptedPassword);
$authAuthenticate = $this->auth->authenticate($this->authAdapter);
if ($authAuthenticate->isValid()) {
$user = $this->authAdapter->getResultRowObject();
$storage = $this->auth->getStorage();
$storage->write(
array(
'email' => $user->email,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'id' => $user->id
)
);
}
I have two problems with this code:
1) I'm saving the session in the database, and the session SaveHandler is configured in a service manager. I don't know if once I'm using Zend\Authenticate I should use the session manager too. In the documentation is saying that
"Unless specified otherwise, Zend\Authentication\AuthenticationService
uses a storage class named Zend\Authentication\Storage\Session, which,
in turn, uses Zend\Session."
So my first question is: can I configure the sessionHandler using just Zend\Authenticate or do I have to use the session manager?
2)I can't figured out how session storage is working in ZF. After login, the session data is not persisted in the DB. If I'm doing some debugging I get the following data:
$session = new Container("FSP");
//this returns the session data
var_dump($session->getIterator());
//this returns empty
var_dump($this->auth->getStorage());
//this returns null, but I do have a FSP named cookie with an Id, showing in Chrome's developer tool
$cookie = $this->getServiceLocator()->get('request')->getHeaders()->get('cookie');
$sessionId = $cookie->FSP;
var_dump($sessionId);
However, if I'm doing a refresh on the login (the login action is run again) the data from the previous session is wrote in the DB and not the data from the current one.
So the second question is, why the session data is not persisted in the database at login and at what step in the session instantiation process is the cookie with the session ID created?
I am using Elliot Haughin's twitter oauth library for codeigniter. It can be found here :
https://github.com/elliothaughin/codeigniter-twitter
I have the following code which authenticates a user with twitter and stores session details.
public function login() {
$this->tweet->set_callback(site_url(''));
$this->tweet->login();
$tokens = $this->tweet->get_tokens();
$user = $this->tweet->call('get', 'account/verify_credentials');
$u = $user->screen_name ;
$data = array(
'user' => $u,
'logged_in' => true
);
$this->session->set_userdata($data) ;
}
This is weird but the logged_in variable is saved whereas the user is not. I am not sure where i am going wrong.
have you include SESSION library or autoload it.
Update:
http://codeigniter.com/user_guide/libraries/sessions.html