Solved

session won't hold value when I am using a header enclude file that is also using the session variable

Posted on 2011-09-26
27
381 Views
Last Modified: 2013-12-13
I have a header include page that floats on top of all other pages. The header has links that appear based on whether a session is open or closed. When I sign in on the sign_in.php I am redirected  to user_account.php which simply echos the value of the session variable. Unfortunately it only echos "no session", plus the header shows no change to the links to indicate that I am now signed in (even if I refresh this user_account page). From their I move to index.php. The header now indicates the user name and a sign_out link as though the header  knows a session is open. From this index page I click sign_out link which goes to the sign_out page and redirects back to index.php in a flash (or refresh) and the header now indicates I am signed out (session closed). So the user_account page does not recognize a session. Can someone help me understand what I am doing wrong? Thanks.


<?php 
//header.php
session_start();
error_reporting(E_ALL);

$username = $signed_in = "";

if (isset($_SESSION['user'])) {
	$username = $_SESSION['user'];
	$signed_in = 1;
} else {$signed_in = 0;}


if ($signed_in === 1) {
	echo '<li><a href="user_acc.php">'."$username".'</a></li>';
	} else {
		echo '<li><a href="crte_acc.php">Create Account</a></li>';
			}

if ($signed_in === 1) {
	echo '<li><a href="sign_out.php">Sign Out</a></li>';
	} else {
		echo '<li><a href="sign_in.php">Sign in</a></li>';
		}



//sign_in.php
include 'header.php';
error_reporting(E_ALL);

if (isset($_POST['submit'])) {
	$_SESSION['user'] = $_POST['username'];
	header("Location: http://www.mysitte.com/cgi-bin/user_acc.php");
}


<form action=" $_SERVER['PHP_SELF'] " method="post" enctype="multipart/form-data">
	<div>
	<div>Username:</div>
		<input name="username" type="text" size="40" maxlength="40"/>
	</div>
		<input name="submit" type="submit" value="Submit" width="99" height="39"/>
	</div>
</form>



//user_account.php
include 'header.php';
error_reporting(E_ALL);

if (isset($_SESSION['user'])) {
	echo $_SESSION['user'];
} else {echo "no session";}



//sign_out.php
include 'header.php';
error_reporting(E_ALL);


if (isset($_SESSION['user'])) {
	destroySession();
	header('Location: http://www.mysitte.com/index.php');
}	else {echo "You are not logged in.";}

function destroySession() {
	$_SESSION=array();
	
	if (session_id() != "" || isset($_COOKIE[session_name()]))
	    setcookie(session_name(), '', time()-2592000, '/');
		
	session_destroy();
}
?>

Open in new window





0
Comment
Question by:kadin
  • 13
  • 6
  • 5
  • +1
27 Comments
 
LVL 8

Expert Comment

by:ropenner
ID: 36602226
if (isset($_SESSION['user'])) is called on line 64 which destroys the session... this occurs right after you set the $_SESSION['user'] in line 33.

I assume you don't want to destroy it based on the session['user'] being set.
0
 

Author Comment

by:kadin
ID: 36602295
Thanks for your response.

I don't understand what you mean by
 ".. this occurs right after you set the $_SESSION['user'] in line 33."

After line 33 the user is redirected to the user_account page not the sign_out page where the session is destroyed.


I am sorry. I don't know what you mean by this. Maybe you can teach me something.
"I assume you don't want to destroy it based on the session['user'] being set."

On the sign_out page does
" if (isset($_SESSION['user'])) {"
 have some effect on the user_account page not showing that it is in session?

0
 
LVL 8

Expert Comment

by:ropenner
ID: 36602346
I think you need an:

exit(1);

on line 34 so that the rest of the php script doesn't get interpretted.

otherwise it is possible to send mutliple header("") commands.

It may help to send each new link to a new tab or window so that you can see each stage of the process.  You can remove this later, but may be helpful to follow the flow of your script.
0
 
LVL 8

Expert Comment

by:ropenner
ID: 36602367
oops I didn't see the comment lines in there stating these are multiple files.  My mistake..  I'll re-read it now.
0
 
LVL 6

Expert Comment

by:neorush
ID: 36602410
It's almost if your session is not quite updating on time, depending on the session storage method, and the redirect the session is probably not written by the time the second page is called, or not getting stored at all.  Try adding an exit here::

if (isset($_POST['submit'])) {
	$_SESSION['user'] = $_POST['username'];
	header("Location: http://www.mysitte.com/cgi-bin/user_acc.php");
	exit();
}

Open in new window

0
 
LVL 8

Assisted Solution

by:ropenner
ropenner earned 167 total points
ID: 36602419
these three files do what you intend I believe.


<?php // sign_in.php
include 'header.php';

if (isset($_POST['submit'])) {
	$_SESSION['user'] = $_POST['username'];
	header("Location: user_account.php");
	exit();
}

?>
<form action=" <?php echo $_SERVER['PHP_SELF'];?> " method="post" enctype="multipart/form-data">
	<div>
	<div>Username:</div>
		<input name="username" type="text" size="40" maxlength="40"/>
	</div>
		<input name="submit" type="submit" value="Submit" width="99" height="39"/>
	</div>
</form>

Open in new window

<?php
//user_account.php
include 'header.php';

if (isset($_SESSION['user'])) {
	echo $_SESSION['user'];
} else {
	echo "no session";
}
?>

Open in new window

<?php // sign_out.php
include 'header.php';

if (isset($_SESSION['user'])) {
	destroySession();
	header('Location: sign_in.php');
	exit();
}	else {
	echo "You are not logged in.";
}

function destroySession() {
	$_SESSION=array();
	
	if (session_id() != "" || isset($_COOKIE[session_name()]))
	    setcookie(session_name(), '', time()-2592000, '/');
		
	session_destroy();
}
?>

Open in new window

0
 
LVL 6

Accepted Solution

by:
neorush earned 167 total points
ID: 36602427
As another note you can test session handling with this page to make sure they are getting stored correctly, the number should increment every time you refresh.
<?php
session_start();
if(!isset($_SESSION['test'])) $_SESSION['test'] = 1;
else $_SESSION['test']++;
echo $_SESSION['test'];
?>

Open in new window

0
 
LVL 8

Expert Comment

by:ropenner
ID: 36602430
forgot header.php  ... 4th file.
<?php 
session_start();
error_reporting(E_ALL);

$username = $signed_in = "";

if (isset($_SESSION['user'])) {
	$username = $_SESSION['user'];
	$signed_in = 1;
} else {
	$signed_in = 0;
}


if ($signed_in === 1) {
	echo '<li><a href="user_account.php">'."$username".'</a></li>';
} else {
	echo '<li><a href="crte_acc.php">Create Account</a></li>';
}

if ($signed_in === 1) {
	echo '<li><a href="sign_out.php">Sign Out</a></li>';
} else {
	echo '<li><a href="sign_in.php">Sign in</a></li>';
}

?>

Open in new window

0
 

Author Comment

by:kadin
ID: 36602446
I have tried exit(). But there was no effect. I also tried
header('refresh: 2; url=
to delay for two seconds before moving to next page.
0
 

Author Comment

by:kadin
ID: 36602477
I tried

<?php
session_start();
$_SESSION['test'] = "1";
if(!isset($_SESSION['test'])) $_SESSION['test'] = 1;
else $_SESSION['test']++;
echo $_SESSION['test'];
?>

Open in new window


It displays the number 2. I think that means that sessions are working.
0
 

Author Comment

by:kadin
ID: 36602528
I changed the sign_in page. Replaced the redirect with a link to user_account page. When the sign_in page refreshes with this link, the header dose not change its links to indicate a session is open. However when I click the link it takes me to the user_account page and displays everything it should including the header links that reveal an open session.  

<?php //sign_in.php
include 'header.php';

error_reporting(E_ALL);

if (isset($_POST['submit'])) {
	$_SESSION['user'] = $_POST['username'];
	echo "You are signed in";
	echo "<a href='user_acc.php'>user account</a>";
	//header("Location: http://www.mysitte.com/cgi-bin/user_acc.php");
	//exit();
}
?>

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 36602535
Session handling is dependent on cookies and all instances of the same browser share the same cookie jar.  So my question is, "Do you see a problem when you have exactly one and only one instance of the browser running?"
0
 

Author Comment

by:kadin
ID: 36602566
Thanks Ray for responding.

I am sorry I don't understand what you mean.

I have been troubleshooting this problem for a weak and a half. I have been opening and closing my browser and clearing or deleting browser history including cookies every time I run a test.

Is this related to what you are asking me?
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 

Author Comment

by:kadin
ID: 36602575
I just tried Safari and get the exact same behavior.
0
 
LVL 6

Expert Comment

by:neorush
ID: 36649973
Your post #36602528 makes it look like everything is working.  header.php would not show the logged in links because it is included before the session variables are set.  But the link to the user_acc.php page does show the links correctly once you follow it since the session info is set.
However, you should get an error if you try and send a header() in signin.php because you have already output info in header.php, you should send the header() before you include header.php
So signin.php should read:
<?php //sign_in.php
error_reporting(E_ALL);
if (isset($_POST['username'])) {
	$_SESSION['user'] = $_POST['username'];
	header("Location: http://www.mysitte.com/cgi-bin/user_acc.php");
	exit(); // stop we are redirecting
}

include('header.php');

?>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data">
	<div>
	<div>Username:</div>
		<input name="username" type="text" size="40" maxlength="40"/>
	</div>
		<input name="submit" type="submit" value="Submit" width="99" height="39"/>
	</div>
</form>

Open in new window

0
 

Author Comment

by:kadin
ID: 36658713
It sounded like what you said made sense. So I moved

 include('header.php');

where you put it. Unfortunately this had no effect. The behavior is the same.

This problem started when I moved to a new web hosting company. Thanks to the help I am receiving from you guys, I am starting to think that the cause is not my programming ignorance alone, but maybe something is set differently in the php.ini file or maybe this new hosting company has a more secure server setting or something. It could also be that I am not receiving all the error messages I could be.
0
 
LVL 6

Expert Comment

by:neorush
ID: 36659905
Try adding this to a .htaccess file to make sure apache (I'm assuming this is apache) is not over riding your error settings:
# show php errors for this site, should be 'off' and '0' for production
	# 'on' and '7' for debugging 
php_flag display_errors on
php_value error_reporting 7

Open in new window

0
 

Author Comment

by:kadin
ID: 36665578
I don't know where the htaccess file is located or if I am allowed to change it.
0
 
LVL 6

Expert Comment

by:neorush
ID: 36666778
Its a file located in a directory on the server, normally in the root of the site.  You may need to create it.
0
 

Author Comment

by:kadin
ID: 36668540
I looked on the sever using filezilla. I couldn't find anything that said htaccess or apache.

I am going to contact my hosting company about this session problem and about error reporting.
0
 

Author Comment

by:kadin
ID: 36669958
Thanks for that info. Let me contact my host provider first. I don't want to mess with anything I am not supposed to. Just so I can feel at ease.
0
 
LVL 6

Expert Comment

by:neorush
ID: 36670823
You can test to see if the error reporting is off or not by make a page with this on it:
<?php
error_reporting('E_ALL');
ini_set('display_errors', 1);
echo $test;

?>
<br />There should be an error above that says something like Notice: Undefined Index....

Open in new window

0
 

Author Comment

by:kadin
ID: 36676440
I created the file you gave me, ran it. It said nothing.

No error file was generated either.
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 166 total points
ID: 36708620
Who is the hosting provider?

Please install and run this test script.  If the session handler is working correctly this script should work predictably.  I would like to eliminate that potential problem first.
<?php // RAY_session_test.php
error_reporting(E_ALL);


// DEMONSTRATE HOW PHP SESSIONS WORK
// MAN PAGE HERE: http://php.net/manual/en/function.session-start.php


// START THE SESSION (DO THIS FIRST, UNCONDITIONALLY, IN EVERY PHP SCRIPT ON EVERY PAGE)
session_start();

// INITIALIZE THE SESSION ARRAY TO SET A DEFAULT VALUE
if (empty($_SESSION["cheese"])) $_SESSION["cheese"] = 1;

// SEE IF THE CORRECT SUBMIT BUTTON WAS CLICKED
if (isset($_POST['fred']))
{
    // ADD ONE TO THE CHEESE
    $_SESSION['cheese']++;
}

// RECOVER THE CURRENT VALUE FROM THE SESSION ARRAY
$cheese = $_SESSION['cheese'];


// END OF PROCESSING SCRIPT - CREATE THE FORM USING HEREDOC NOTATION
$form = <<<ENDFORM
<html>
<head>
<title>Session Test</title>
</head>
<body>
Currently, SESSION["cheese"] contains: $cheese<br/>
<form method="post">
<input type="submit" value="increment this cheese" name="fred"  />
<input type="submit" value="leave my cheese alone" name="john" />
</form>
</body>
</html>
ENDFORM;

echo $form;

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 36708630
Also, if you want to see the design pattern that most sites use for PHP client authentication, this article may be helpful.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html
0
 

Author Closing Comment

by:kadin
ID: 36712289
Problem solved.

I told my host provider that experts-exchange experts can't find anything wrong with my script and that I think it is something about the server or a setting or something. They discovered the problem was that my php scripts were located in the cgi-bin folder and that was only for perl scripts. I did not have a cgi-bin folder on my last host provider and I thought I remember either my new host provider told me or I read somewhere that the php scripts go in the cgi-bin folder.

I learn something. Thank you all for your efforts. Your comments were helpful to help me learn new things.
0
 

Author Comment

by:kadin
ID: 36713218
Thanks for that article you wrote RAY. That looks helpful.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now