Forum Moderators: coopster

Message Too Old, No Replies

Sessions is reset upon page refresh

         

paseo

5:58 am on Jan 30, 2008 (gmt 0)

10+ Year Member



Hi,

I just want to say thanks to any help in advance.

I have a webpage that is setup to use PHP sessions. I am using an IF ELSE statement to determine whether to show a login box, or a welcome message. When i login, it successfully recognizes that i have logged in and displays the welcome message as opposed to the login box. Upon refresh of the page or if i navigate away and come back, the login box appears again as if my session does not exist anymore.

My question, how can i set it up so that my session will remain active until i either logout, or close the IE window all together. I dont want my session to be terminated if i just navigate away from the page or refresh it

THANKS!

cameraman

7:59 am on Jan 30, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Without seeing any code, it sounds like you're not actually writing the session data. If you don't have session.auto_start on, you need to call session_start() [php.net] before writing or reading any session data.
If you know that not to be the case, you may have some flaw in your logic - we'll need to see some snippets!

paseo

2:21 pm on Jan 30, 2008 (gmt 0)

10+ Year Member



As requested, i am attaching the code for the page. To quickly give a run down, i have an if else statemetn that will either display a Welome message or display a login box. If it displays a login box, upon submition, the values for $_SESSION['username'] and $_SESSION['password'] are populated from the POST. From this, a query is generated to select * from table where username = $_SESSION['username'] etc.... This should return 1 row. I am also fetching an array for that row to populate other items such as first name, last name, address etc...The IF statemenet if ( mysql_num_rows( $query ) == 1 ) will be true when the row is fetched. If nothing is found, the statement will be false and will display the form to login.

Here is the code...Am i doing something that is not commonly practiced or is my code not up to par?

THANKS!

<?php

session_start();

include ("/var/secure/db.php");

$sql = mysql_connect("$db_ip","$db_user","$db_pass");
if (! $sql) {
die('Could not connect to server: ' . mysql_error());
}
elseif(! mysql_select_db("$db_name", $sql)){
die('Could not open database: ' . mysql_error());
}

$_SESSION['username'] = mysql_real_escape_string($_POST['username']);
$_SESSION['password'] = mysql_real_escape_string($_POST['password']);

$select = "select * from table
where username = '" . $_SESSION['username'] . "'
and password= '" . $_SESSION['password'] . "'";

$query = mysql_query( $select );

$array = mysql_fetch_array($query);

$_SESSION['firstname'] = $array['firstname'];
$_SESSION['lastname'] = $array['lastname'];
$_SESSION['address'] = $array['address'];
$_SESSION['city'] = $array['city'];
$_SESSION['state'] = $array['state'];
$_SESSION['zipcode'] = $array['zipcode'];
$_SESSION['homephone'] = $array['homephone'];
$_SESSION['workphone'] = $array['workphone'];
$_SESSION['email'] = $array['email'];

?>

<?php

if ( mysql_num_rows( $query ) == 1 )
{
echo "<strong>Welcome ",$_SESSION['firstname']," ",$_SESSION['lastname'],"</strong> ¦ ","<a href='#' title='My Account'>My Account ¦ </a>","<a href='#' title='Logout'>Logout ¦</a>";
}
else
{
echo "<form name='login' action='' method='post'>";
echo "User Name:<input name='username' type='text' title='User Name' />";
echo "Password:<input name='password' type='password' title='Password' />";
echo "<input type='submit' value='Go' />";
echo "</form>";
}

?>

PHP_Chimp

2:31 pm on Jan 30, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Not that this helps with your sessions but your database connect/select could be written in 2 lines.

$sql = mysql_connect("$db_ip","$db_user","$db_pass") or die('Could not connect to server: '.mysql_error());
mysql_select_db("$db_name", $sql) or die('Could not ...');

Have you checked your sessions using a constant value? Like $_SESSION['email'] = 'test@example.com';
As if you get test@ then the problem lies with the database and not the sessions.

paseo

2:35 pm on Jan 30, 2008 (gmt 0)

10+ Year Member



the array is working as the only variables manually defined are from the two POST actions. The $_SESSION['firstname'] is pulled from the DB via the array and is successfully displayed on the welcome message once authenticatdd. The only way it can populate the $_SESSION['firstname'] is from the array pulling it from the row from $query which is a DB call. Right?

Also, I just wanted to make a comment about my initial post. I said i dont want the session to be terminated when i navigate away or refresh the page. Refreshing the page will actually resubmit the POST and will tehrefore give the desired result...so in actuallity, i dont want the session to terminate if i navigate away and then come back...

paseo

4:01 pm on Jan 30, 2008 (gmt 0)

10+ Year Member



Ok, it works with the below code but I am unsure whether this is the correct approach. Can you please look over it and let me know. I have added an if else statement to determine whether there are values for $_SESSION variables. I have also included a logout function. Is this correct as well. THANK YOU SO MUCH!

<?php

session_start();

include ("/secure/db.php");

$sql = mysql_connect("$db_ip","$db_user","$db_pass");
if (! $sql) {
die('Could not connect to server: ' . mysql_error());
}
elseif(! mysql_select_db("$db_name", $sql)){
die('Could not open database: ' . mysql_error());
}

if ($_SESSION['id']) {
}
else
{
$_SESSION['username'] = mysql_real_escape_string($_POST['username']);
$_SESSION['password'] = mysql_real_escape_string($_POST['password']);

$select = "select * from table
where username = '" . $_SESSION['username'] . "'
and password= '" . $_SESSION['password'] . "'";

$query = mysql_query( $select );

$array = mysql_fetch_array($query);

$_SESSION['id'] = $array['id'];
$_SESSION['firstname'] = $array['firstname'];
$_SESSION['lastname'] = $array['lastname'];
$_SESSION['address'] = $array['address'];
$_SESSION['city'] = $array['city'];
$_SESSION['state'] = $array['state'];
$_SESSION['zipcode'] = $array['zipcode'];
$_SESSION['homephone'] = $array['homephone'];
$_SESSION['workphone'] = $array['workphone'];
$_SESSION['email'] = $array['email'];
}

function logout()
{
$_SESSION = array();

session_destroy();
setcookie("username", NULL, time()-3600);
setcookie("password", NULL, time()-3600);

header("Location: index.php");

}

if (isset($_GET["logout"]))
logout();

?>

<?php

if ($_SESSION['id'])
{
echo "<strong>Welcome ",$_SESSION['firstname']," ",$_SESSION['lastname'],"</strong> ¦ ","<a href='#' title='My Account'>My Account ¦ </a>","<a href='#' title='Logout'>Logout ¦</a>";
}
else
{
echo "<form name='login' action='' method='post'>";
echo "User Name:<input name='username' type='text' title='User Name' />";
echo "Password:<input name='password' type='password' title='Password' />";
echo "<input type='submit' value='Go' />";
echo "</form>";
}

?>

cameraman

6:52 pm on Jan 30, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I can see what's probably happening in the first code you posted - if you navigate back to the page, there's no post data so you look up nobody and overwrite your session variables. What I generally do is check for the existence of a post variable, usually my submit button, to decide whether or not to do any form processing:
if(isset($_POST['submit'])) {
// process form
} // EndIf form submitted

Your revision is ok but it's a good idea to get into the habit of checking for an empty result from a query:
$query = mysql_query( $select );
if(mysql_num_rows($query)) {
$array = mysql_fetch_array($query);

$_SESSION['id'] = $array['id'];
.
.
} // EndIf got valid name/pass

As a side note, if the variables used in your connect line are strings you don't really need the quotes - they don't hurt anything, but it's extra typing ;)
$sql = mysql_connect($db_ip,$db_user,$db_pass);

And another side note (there's nothing wrong with the way you're doing it), you can refer to array elements inside quotes by surrounding them with curly braces:
$select = "select * from table
where username = '{$_SESSION['username']}'
and password= '{$_SESSION['password']}'";

Good work, really you figured it out on your own.

paseo

6:59 pm on Jan 30, 2008 (gmt 0)

10+ Year Member



Cameraman, Thank you very much! I will make note of all your recomendations. I have another question, but is unrelated to this and will start a new thread.

Thanks Again!

PHP_Chimp

7:02 pm on Jan 30, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I didnt see before but noticed
setcookie("password", NULL, time()-3600);

when you were destroying your session cookies.

Am I correct in assuming that you are storing a password in a cookie?

I put it in the session, as cookies are written in plan text and assuming you are using http not https these will be available for all to see. As the session cookie links the person to there session data you can store passwords in the session and use those when they are needed.

paseo

7:13 pm on Jan 30, 2008 (gmt 0)

10+ Year Member



I didn't set it up to use cookies but was unde rthe impression it automatically creates one...I put those in there for good measure in case a cookie is created with username and password values...I am under the impression that all my variables are $_SESSION variables and I am not using cookies...at least on purpoese..:)

PHP_Chimp

8:08 pm on Jan 30, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The only cookie that should be created by default is the session id cookie.
As this is used to tie the session on the browser to the session data on the server. There shouldn't be any other cookies set by the session, unless people ask for them to be set.
So there shouldnt be a password cookie, although I guess killing it in case is never a bad idea ;)