$_SESSION and header("Location:")

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
olog-hai
Forum Commoner
Posts: 34
Joined: Thu May 31, 2007 8:47 am
Location: Québec city, QC, Canada

$_SESSION and header("Location:")

Post by olog-hai »

Hi,

I'm experimenting problem with redirection and session.

here is a working situation.

The user login on the home page, the post form button call login.php, the login.php create the session and redirect to another page. All is ok. :lol:

here is a not working situation.

The user login on the home page, the post form button call login.php, the login.php create the session, and redirect to another page and this page redirect to another page. My session is lost. 8O

why :?:

thanks.
GuitarheadCA
Forum Newbie
Posts: 20
Joined: Fri Jul 13, 2007 12:59 am

Post by GuitarheadCA »

Be sure to include the function session_start() at the top of EVERY page. If a user goes to a page without this declared, all session data will be lost.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

session_write_close() may be of interest.
Phoenixheart
Forum Contributor
Posts: 123
Joined: Tue Nov 16, 2004 7:46 am
Contact:

Post by Phoenixheart »

No, to my (very limited :? ) knowledge, session data won't be lost even when session_start() isn't called.
A cookie-based session is ( :D ) a cookie stored on the client machine, and it won't go anywhere unless you force it to.
You only have to call session_start() if you want to access session variables...
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

Post your code.
User avatar
olog-hai
Forum Commoner
Posts: 34
Joined: Thu May 31, 2007 8:47 am
Location: Québec city, QC, Canada

Post by olog-hai »

Ok,

I found that when I'm logged and I hit F5 to refresh the page I lost my session :cry: .

ok here is my code ('/lib/session.php') that I include on every page.

Code: Select all

<?
	session_start();

	include($_SERVER['DOCUMENT_ROOT'].'/lib/objects/session.php');

	$ERROR_UNSERIALIZE = 3;
	
	if ( isset( $_SESSION['session'] ) ){
		$objSession = unserialize( $_SESSION['session'] );
		if ( empty($objSession) ){
			unset( $_SESSION['session'] );
			$_SESSION['error'] = $ERROR_UNSERIALIZE;
			header("Location: /");
	     	exit;
		}

		$lan = strtolower( $objSession->Member->langue );
		
	}else{
		if( isset( $_SESSION['langue'] ) ){
			if ( isset($GP_l) ){
				$_SESSION['langue'] = $GP_l;
			}
		}else{
			$_SESSION['langue'] = 'en';
		}
		$lan = $_SESSION['langue'];
	
		$objSession =& new Session();	
	}
?>
login.php

Code: Select all

<?php
	// ACCESS //
	include ($_SERVER['DOCUMENT_ROOT'].'/lib/session.php');
	
	# constante d'erreur de login
	$ERROR_LOGIN = 1;

 	if ( $objSession->Member->login( $GP_txtUsager, $GP_txtPassword )){

		try{
		
			$query_config_membre = "call Config_Membre_Get(".$objSession->Member->num_membre.");";
			$objSession->MySQL->executeSP( $query_config_membre );
			
			# conserve les données obtenu.
			$Config = $objSession->MySQL->store_result()->fetch_object();
			$objSession->MySQL->free_result();
				
		}catch ( UTException $e ){
			echo $e->getError();
			exit;
		}catch ( Exception $e ){
			echo $e->getCode()."<br>".$e->getMessage()."<br>".$e->getTraceAsString();
			exit;
		}

 		
	}else{
		
		unset( $_SESSION['session'] );
		$_SESSION['error'] = $ERROR_LOGIN;
		header("Location: /");
     	exit;
	}
	
	$objSession->sess_quete_num = 1;
	$_SESSION['session'] = serialize( $objSession );
	#session_write_close();

	
	if( $Config->num_defaut_personnage ){
		header("Location: /quest/character/overview/");
	}else{
		header("Location: /quest/member/character/");
	}
?>
I tried session_write_close(), but no cigar.

Here is the behavior: On my home.php I log me in, the form post redirect me to the login.php, the code above create the session and redirect me with header location to another page like securedpage.php, I print_r() the object and all my information is correct. I Hit refresh and the print_r() show me an empty object. My session is lost and I have to re-login.

Note that the $_SESSION['session'] content an object. I use serialize, and unserialize.

I lost some many hours on that stupid bug :x , I noted that this bug appears when I added an instance of Member Object in my session object.


here is a print_r() of my object.

Code: Select all

Session Object
(
    # mySQL Object is a singleton.
    [_MySQL] => mySQL Object
        (
        )

    [_Member] => Member Object
        (
            
            [_MySQL] => mySQL Object
                (
                )

            [_num_membre] => 42
            [_usager] => o
            [_langue] => en
            [_points_remaining] => 1000
            [_bg_color] => _gray
            [_top_menu] => 1
            [_left_menu] => 0
            [_tool_tip] => 1
            [_resolution] => 780
            [_nom] => 
            [_prenom] => 
            [_nomclan] => 
            [_adresseweb] => 
            [_pays] => 
            [_email] => 
            [_email_cell] => 
            [_age] => 0000-00-00
            [_sexe] => 
            [_photo] => 
            [_icq] => 0
            [_clan] => 
            [_date] => 0000-00-00 00:00:00
            [_id_unique] => 
            [_accepte] => 
            [_adressewebclan] => 
            [_locked] => 
            [_parain] => 0
            [_warning] => 0
        )

    [_sess_db_name] => UnwrittenTales
    [_sess_error] => 0
    [_sess_perso_num] => 0
    [_sess_perso_nom] => 
    [_sess_perso_statut] => 0
    [_sess_quete_num] => 1
    [_sess_quete_jour] => 0
    [_sess_quete_annee] => 0
)
I use Firefox 2.0.0.5 and IE 7.0.5730.11

I use local WAMP5 Version 1.7.1

Created by Romain Bourdon (romain@anaska.com)
Powered by Anaska http://www.anaska.com
Sources are available at SourceForge
http://www.wampserver.com

to host apache and mysql on my windows XP Pro. After I check-in my code on my linux box with eclipse and cvs.

Thanks for your time :roll: .
miro_igov
Forum Contributor
Posts: 485
Joined: Fri Mar 31, 2006 5:06 am
Location: Bulgaria

Post by miro_igov »

I hope you do not use the block

Code: Select all

if ( $objSession->Member->login( $GP_txtUsager, $GP_txtPassword )){
.....
}else{
 unset( $_SESSION['session'] );
 $_SESSION['error'] = $ERROR_LOGIN;
 header("Location: /");
 exit;
} 

on the page to which login.php redirects. It will be helpful to post it too, because it looks like the problem is coming from it.
User avatar
olog-hai
Forum Commoner
Posts: 34
Joined: Thu May 31, 2007 8:47 am
Location: Québec city, QC, Canada

Post by olog-hai »

Hi,

Code: Select all

if ( $objSession->Member->login( $GP_txtUsager, $GP_txtPassword )){ 
..... 
}else{ 
 unset( $_SESSION['session'] ); 
 $_SESSION['error'] = $ERROR_LOGIN; 
 header("Location: /"); 
 exit; 
} 

header("Location: /quest/member/character/");
This block redirect the user to the home.php like you see in header("Location: /"); and display the error msg. When the login is sucessful the redirect is header("Location: /quest/member/character/"); , that's mean index.php on that directory here is the code from the page:

Code: Select all

index.php
<?
	include ($_SERVER['DOCUMENT_ROOT'].'/lib/session.php');
	$objSession->valid_access( ACCESS_ALL );

	// UTILITIES //
	include($_SERVER['DOCUMENT_ROOT'].'/lib/objects/tooltips.php');
	include('member.character.php');
	// TEMPLATES //
	include($_SERVER['DOCUMENT_ROOT'].'/lib/templates/top.php');
	include($lan.'.php');		

 	$objSession->display_validation();
 	
	$objSession->select_database(); 
 	$objTooltips =& new Tooltips();
 	$help = $objTooltips->getContent( "profile_character%" );
  	
	$onglet = 1;
	if( $GP_o > 0 && $GP_o < 2)
		$onglet = $GP_o;

	$objCharacter =& new Member_Character();
    $objCharacter->getAllCharacter( $vivant, $mort );

?>
...
html
...
<pre><? print_r($objSession); ?></pre>

<?
	include($_SERVER['DOCUMENT_ROOT'].'/lib/templates/bot.php');
?>
All is ok the first time, but when I hit refresh, my session is lost.

thanks
Charles256
DevNet Resident
Posts: 1375
Joined: Fri Sep 16, 2005 9:06 pm

Post by Charles256 »

is http://www.php.net/session_start called at the top of every page?
User avatar
olog-hai
Forum Commoner
Posts: 34
Joined: Thu May 31, 2007 8:47 am
Location: Québec city, QC, Canada

Post by olog-hai »

Charles256 wrote:is http://www.php.net/session_start called at the top of every page?

Code: Select all

<? 
        session_start(); 

        include($_SERVER['DOCUMENT_ROOT'].'/lib/objects/session.php'); 

        $ERROR_UNSERIALIZE = 3; 
        
        if ( isset( $_SESSION['session'] ) ){ 
                $objSession = unserialize( $_SESSION['session'] ); 
                if ( empty($objSession) ){ 
                        unset( $_SESSION['session'] ); 
                        $_SESSION['error'] = $ERROR_UNSERIALIZE; 
                        header("Location: /"); 
                exit; 
                } 

                $lan = strtolower( $objSession->Member->langue ); 
                
        }else{ 
                if( isset( $_SESSION['langue'] ) ){ 
                        if ( isset($GP_l) ){ 
                                $_SESSION['langue'] = $GP_l; 
                        } 
                }else{ 
                        $_SESSION['langue'] = 'en'; 
                } 
                $lan = $_SESSION['langue']; 
        
                $objSession =& new Session();    
        } 
?>
Yes.

This code is included on every page.
miro_igov
Forum Contributor
Posts: 485
Joined: Fri Mar 31, 2006 5:06 am
Location: Bulgaria

Post by miro_igov »

Do you use this redirection block in every your script? Is this

Code: Select all

$objSession->Member->login( $GP_txtUsager, $GP_txtPassword )
return true even if there is no POST with the user/password ?
User avatar
olog-hai
Forum Commoner
Posts: 34
Joined: Thu May 31, 2007 8:47 am
Location: Québec city, QC, Canada

Post by olog-hai »

Hi,

Code: Select all

$objSession->Member->login( $GP_txtUsager, $GP_txtPassword )
return false on no match, true if match.

this script is used only when user login.

here is the script that is ran when I login.


/lib/session.php

Code: Select all

<?php
	session_start();

	include($_SERVER['DOCUMENT_ROOT'].'/lib/objects/session.php');
	
	//selection securitaire des variables GET et POST
	//les variable GET sont ecraser si les POST on le meme nom
	//tous les variable sont accessible avec le prefixe 'GP_' ex: GP_txtUsager
	import_request_variables("gp", "GP_");
	
	# constante d'erreur de sérialisation
	$ERROR_UNSERIALIZE = 3;
	
	if ( isset( $_SESSION['session'] ) ){
		$objSession = unserialize( $_SESSION['session'] );
		if ( empty($objSession) ){
			unset( $_SESSION['session'] );
			$_SESSION['error'] = $ERROR_UNSERIALIZE;
			header("Location: /");
	     	exit;
		}

		$lan = strtolower( $objSession->Member->langue );
		
	}else{
		if( isset( $_SESSION['langue'] ) ){
			if ( isset($GP_l) ){
				$_SESSION['langue'] = $GP_l;
			}
		}else{
			$_SESSION['langue'] = 'en';
		}
		$lan = $_SESSION['langue'];
	
		$objSession =& new Session();	
	}
?>
login/login.php

Code: Select all

<?php
	include ($_SERVER['DOCUMENT_ROOT'].'/lib/session.php');
	
	$ERROR_LOGIN = 1;

 	if ( $objSession->Member->login( $GP_txtUsager, $GP_txtPassword )){

		# Ce header decide de la page home de l'usager sur UnwrittenTales
		# verifie si il ya un monde par defaut et le redirige 
		
		try{
		
			$query_config_membre = "call Config_Membre_Get(".$objSession->Member->num_membre.");";
			$objSession->MySQL->executeSP( $query_config_membre );
			
			# conserve les données obtenu.
			$Config = $objSession->MySQL->store_result()->fetch_object();
			$objSession->MySQL->free_result();
				
		}catch ( UTException $e ){
			echo $e->getError();
			exit;
		}catch ( Exception $e ){
			echo $e->getCode()."<br>".$e->getMessage()."<br>".$e->getTraceAsString();
			exit;
		}

 		
	}else{
		
		unset( $_SESSION['session'] );
		$_SESSION['error'] = $ERROR_LOGIN;
		header("Location: /");
     	exit;
	}
	
	$objSession->sess_quete_num = 1;
	$_SESSION['session'] = serialize( $objSession );

	
	if( $Config->num_defaut_personnage ){
		header("Location: /quest/character/overview/");
	}else{
		header("Location: /quest/member/character/");
	}
?>
/quest/member/character/index.php

Code: Select all

<?
	// ACCESS //
	include ($_SERVER['DOCUMENT_ROOT'].'/lib/session.php');
	$objSession->valid_access( ACCESS_ALL );

	// UTILITIES //
	include($_SERVER['DOCUMENT_ROOT'].'/lib/objects/tooltips.php');
	include('member.character.php');

	// TEMPLATES //
	include($_SERVER['DOCUMENT_ROOT'].'/lib/templates/top.php');
	include($lan.'.php');		

 	$objSession->display_validation();
 	
	$objSession->select_database(); //sélectionne la db unwrittentales.

 	$objTooltips =& new Tooltips();
 	$help = $objTooltips->getContent( "profile_character%" );
  	
	$onglet = 1;
	if( $GP_o > 0 && $GP_o < 2)
		$onglet = $GP_o;

	$objCharacter =& new Member_Character();
                $objCharacter->getAllCharacter( $vivant, $mort );

?>

HTML ...

<pre><? print_r($objSession); ?></pre>

<?
	include($_SERVER['DOCUMENT_ROOT'].'/lib/templates/bot.php');
?>

To get this page /quest/member/character/index.php we have to be logged, so the first time i'm logged, and when I refresh the page /quest/member/character/index.php with F5, I lost session.

Any Idea why ?

Is my object too big ? What is the reason that the session is disapears, this code always works til I added Member class instance in my session object class.

thanks
miro_igov
Forum Contributor
Posts: 485
Joined: Fri Mar 31, 2006 5:06 am
Location: Bulgaria

Post by miro_igov »

Try debugging it. What i do in such cases is placing print_r($_SESSion); die; after every include (if you call any methods in the include files) and after calling methonds in teh current script, starting from the beginning.

You will see what destroys the session.
User avatar
olog-hai
Forum Commoner
Posts: 34
Joined: Thu May 31, 2007 8:47 am
Location: Québec city, QC, Canada

Post by olog-hai »

miro_igov wrote:Try debugging it. What i do in such cases is placing print_r($_SESSion); die; after every include (if you call any methods in the include files) and after calling methonds in teh current script, starting from the beginning.

You will see what destroys the session.
I use print_r at the end of quest/member/character/index.php, look in above post. There is a live session at the end of script. When I refresh the page, the first page executed is /lib/session.php, and there is no session. I cant debug deeper than that. the only thing I suspect is that the session_start isn't find the cookie session.

Any other tips, hints, idea :idea: ?

Thanks.
User avatar
olog-hai
Forum Commoner
Posts: 34
Joined: Thu May 31, 2007 8:47 am
Location: Québec city, QC, Canada

Post by olog-hai »

Ok I found something else

My cookie or file that keep my session is always deleted when I refresh my page.

any Idea ?

thanks
Post Reply