PHP Session gets destroyed after redirection? - php

I am facing a very strange problem , i am doing CasLogin in my application..
i have successfully implemented CAS, i.e all values are set in $_SESSION variable after all proper validations, and successful login, but when i redirect it from CasLogin() action to Index Action $_SESSION contains nothing..
i am using Yii Frame Work.
here is code.
public function actionCasLogin($CID=NULL)
{
//code to be imported from GMS here
PhpCasControl::setPhpCasContext($CID);
phpCAS::setPostAuthenticateCallback(array($this,'_saveServiceTkt'));
$loginForm = new CasLoginForm;
// validate user input and redirect to the previous page if valid
if ($loginForm->login($CID)) {
if (Yii::app()->user->isGuest){
echo '<br> <br> This shows up..';
var_dump($_SESSION);
}
else{
echo 'Hello at caslogin <br>never shows up';
var_dump(Yii::app()->user->id);
}
$this->redirect(array('index'));
}
else {
throw new Exception("You don't have sufficient permissions to access this service. Please contact Administrator !");
}
}
this function Works Properly and if i put a EXIT; here it will display $_SESSION with all the desired values..
but after redirection... to index..
whose code is this..
public function actionIndex()
{
echo"hello at index";
if (! Yii::app()->user->isGuest) {
//#CASE 1: User is already logged in
$this->redirect(array("site/upload"));
}
else{
//#CASE 2: User is not Logged in
echo '<br>shows up with empty session<br>';
var_dump($_SESSION);
var_dump(Yii::getVersion());
exit;
$this->redirect(array("site/login"));
}
}
here $_SESSION is empty..
any explanation why this might be happening..
i am aware of CAS creating its own session by service ticket name.. i have handled that thing.. by RenameSession function, which i call in CasLoginForm..
whose code is this..
public function rename_session($newSessionId) {
//Store current session variables so that can be used later
$old_session = $_SESSION;
//Destroy current session
session_destroy();
// set up a new session, of name based on the ticket
$session_id = preg_replace('/[^a-zA-Z0-9\-]/', '', $newSessionId);
//start session with session ID as 1) service ticket in case of CAS login, 2) random sTring in case of local login.
session_id($session_id);
session_start();
//echo "<br>new session <br>";
//Restore old session variables
$_SESSION = $old_session;
//var_dump($_SESSION);
}

OK, i think that you should use session_id to change the id.
public function rename_session($newSessionId) {
// set up a new session id, of name based on the ticket
session_id(preg_replace('/[^a-zA-Z0-9\-]/', '', $newSessionId));
}

Related

How to redirect back to previous page after login in Code Igniter?

Okay, so this is what I do:
I go to www.mywebsite.com/orders?id=1
It redirects be to login before proceeding.
I log in successfully but it redirects to www.mywebsite.com/orders.
If I am already logged in and go directly using GET method, it works fine. But if I am asked to login, the GET method disappears.
How do I preserve ?id=1?
Before redirecting the user back to the login page store the current page (the requested page) in a session variable. Assuming you have a function called check_login this would more or less look like what you should do:
public function check_login() {
if (!$this->session->has_userdata('logged_in') || $this->session->logged_in !== true) {
if (!empty($_SERVER['QUERY_STRING'])) {
$uri = uri_string() . '?' . $_SERVER['QUERY_STRING'];
} else {
$uri = uri_string();
}
$this->session->set_userdata('redirect', $uri);
redirect('/auth/login');
}
}
Then when the user successfully logs in your login function should somewhere have the following logic:
public function login() {
// form validation
// get post vars
// check username/pwd against db
if ($login) {
if ($this->session->has_userdata('redirect')) {
redirect($this->session->redirect);
} else {
redirect('/dashboard');
}
} else {
// error logging in
}
}
session variable could store the id.While log in using session pass the id value.You can retrive the value anywhere in session.
$this->load->library('session');
$this->session->set_userdata('userId', 'YourId');
where userId would be the name of the session variable, and YourId would be the value.
Simply Use this
redirect($_SERVER['HTTP_REFERER']);

logout issue in smarty template engine

I've got a small problem with my smarty project, logout problem to be precise. I have a index.php page which is the "main" page and it gets POST data and directs actions based on current data. There`s checking if the session variables has been set. Now when I login I have function like this:
function login($value)
{
$res = $this->sql->checkLogin($value);
if($res)
{
//checks if user is admin
$isadm = $this->sql->isAdm($value);
if($isadm == true)
{
$_SESSION['user'] = $value['name'];
$_SESSION['adm'] = true;
$message = 'Admin';
$this->tpl->assign('var', $message);
if($_SESSION['adm'] == true)
{
//sets some variables for admin users
$navigation = 'navi';
$this->tpl->assign('navigation', $navigation);
}
$this->tpl->display('maint_main.tpl');
}
//user is not admin
else
{
$_SESSION['user'] = $value['name'];
$_SESSION['adm'] = false;
$message = 'Perus';
$this->tpl->assign('var', $message);
if($_SESSION['adm'] == true)
{
$navigation = 'navi';
$this->tpl->assign('navigation', $navigation);
}
$this->tpl->display('maint_main.tpl');
}
}
//login failes, show login form and info
else
{
$message = 'Login failed';
$this->tpl->assign('var', $message);
$this->tpl->display('login_form.tpl');
}
}
and logout function :
function logout()
{
setcookie(session_name(), '', time()-42000, '/');
session_unset();
session_destroy();
$this->tpl->display('login_form.tpl');
}
These work just about the way they are supposed to but the real problem occurs when I log out and redirect to the login_form.tpl. If I use the back button of the browser the POST data with username and password is retrieved and the login goes through again. This causes that those pages behind login are still viewable. As I am not quite familiar with Smarty yet I couldn`t figure out any way to fix this. So basically how to prevent access to that POST data after logout?
I don't think this has anything to do with smarty. This is a browser/http generic issue. Most browsers will re-post form data after confirmation from the user.
One approach to make re-posts of the form invalid would be to pass along a secret code/token (perhaps a guid or your session id) which is also stored in session data. When the user logs out, clear their session (or at least the secret code you're checking). When the user logs in, check to make sure that the confirmation code matches the one for the current session.
This pattern is often used to manage csrf attacks and is often known as a 'synchronizer token'. This blog post provides a good explanation https://blog.whitehatsec.com/tag/synchronizer-token/

Session is destroyed on page refresh in PHP

I am developing a web application using PHP in which a user initially has to sign in and view his content. I am using PHP sessions to maintain state. I encountered following problems:
Although I started the session on each page and after relevent session variables are set, the session is destroyed each time the page is refreshed or when I browse the same URL on a different tab.
I need the user to be redirected to his content page when the user browsed login page with he has already logged in.
I'm really new to PHP, So I have no idea how to solve these problems. I referred several questions in the stackoverflow, but they all say that sessions are not destroyed on page refresh. I could not understand what's wrong with my page. Any solution with explaination is greatly appreciated.
Login page
<?php
session_start();
class Sessions{
public static function setSessionState($userdata){
unset($userdata['password']);
unset($userdata['timestamp']);
$_SESSION['user']=$userdata;
}
}
if(isset($_POST['username']) && isset($_POST['password'])){
$dbcon = new DBConnection();
$dbcon->connect();
$username= strip_tags(stripslashes(trim($_POST['username'])));
$password = strip_tags(stripcslashes($_POST['password']));
echo "<script>alert($username);</script>";
$result = $dbcon->getUser($username,$password);
if(mysqli_num_rows($result)==1){
$user = $dbcon->getUserData($result); #getUserData function accepts mysqli result as an input and returns a row(array) of user details.
if(isset($user)){
Sessions::setSessionState($user);
header("location:index.php");
}
else{
echo "user variable is not set!!!";
}
}
else if(mysqli_num_rows($result)==0){
echo "Login error! Username or Password incorrect!";
}
else{
die("Unknown Error occured!");
}
}
............
Index page(in which user's private content is visible)
<?php
session_start();
if(isset($_SESSION['user'])){
print_r($_SESSION['user']);
}
else{
echo "session variable not set";
}
?>
Thank you.
I finally found the answer which is actually my bad. I didn't mention the last part of the index.php file as I though that part is irrelevant.In that part I have a part,
<form action="<?php session_destroy(); ?>">
After commenting that session_destroy() method call, I could solve my problem and keep session alive.
Sorry for incomplete code.
try this
class Sessions{
public static function setSessionState($userdata){
if ( !isset($_SESSION['user']) ) {
$_SESSION['user'] = $userdata;
}
}
}

Session persistence with Zend framework

I'm having problems with storing variables in a $_SESSION variable.
I'm using Zend framework and building a 3 step application form. Now, when the first step is done, I store the data in MySQL database, and store the returned insert id in a session variable. Then I forward the page to another controller (step 2). When I forward the request, everything works fine and I can read the id from the session variable. But when I submit the second form (which has the same controller of step 2 as an action) the session is lost. I try to var_dump it, and it returns NULL.
Here's the code:
public function organizationAction()
{
$this->view->vals="";
$form=$this->getOrganizationForm();
$this->aplid=$_SESSION['appid'];
var_dump($_SESSION);
$firsttime=$this->getRequest()->getParam('firsttime',0);
//if(null==$this->aplid) $this->_forward('index','index');
if ($this->getRequest()->isPost() && $firsttime==0) {
if (!$form->isValid($_POST)) {
// Failed validation; redisplay form
$this->view->form = $form;
return false;
}
var_dump($_SESSION);
$values = $form->getValues();
$db=new Util_Database();
if($db->insertOrganization($values,$this->aplid))
$this->_forward('final');
else echo "An error occured while attempting to submit data. Please try agian";
}
$this->view->form=$form;
}
What is the problem here? I tried storing the session_id in the form, and then setting it before session_start(), but it starts a whole new session. Please help!
I'm not sure if this is going to help, because I'm not sure if something else might be happening in step 2. But here goes.
You might be inadvertently overwriting your session data. Here is what I came up with that might help give some ideas.
public function organizationAction() {
$this->view->vals = "";
$form = $this->getOrganizationForm();
$db = new Util_Database();
//This will only submit the form if the is post and firsttime == 0
if ($this->getRequest()->isPost() && $this->getRequest()->getPost('firsttime') == 0) {
//if form is valid set session and save to db
if ($form->isValid($this->getRequest()->getPost())) {
//We only want to initialize the session this time, if we do it
//on the next pass we may overwrite the information.
//initialize session namespace
$session = new Zend_Session_Namespace('application');
//get values from form, validated and filtered
$values = $form->getValues();
//assign form value appid to session namespace
$session->appid = $form->getValue('appid');
//assign session variable appid to property aplid
$this->aplid = $session->appid;
if ($db->insertOrganization($values, $this->aplid))
$this->_forward('final');
else
echo "An error occured while attempting to submit data. Please try agian";
} else {
//if form is not vaild populate form for resubmission
//validation errors will display of form page
$form->populate($this->getRequest()->getPost());
}
}
//if not post display form
$this->view->form = $form;
}
P.S. If your gonna go ZF...Go ZF! :)

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