Jump to content
xisto Community
joe.k

Php Session Problem

Recommended Posts

i have downloaded easyphp on my PC and i am a bit noob with php mysql commands.i have a problem making session work the problem that the session file in my server get deleted after leaving the page where the session was start for the first time.the problem that the session can only be used within the creation page unless you leave it.why?? i have no idea ... i have been looking around for three days now ..thank in advance for any help. if you need more details let me know ;).Joe.k

Share this post


Link to post
Share on other sites

Well, before I try and figure out some server setting issue that I'm not very good at, I'll try the most obvious stuff first.

At the beginning of every page, you need to start a session. The best part about this function is that it starts a new session if one doesn't exist and retrieves the session information for one that does exist.

<?phpsession_start();

Then you have to get your session ID:

<?phpsession_start();$session_id = session_id();

Finally, you usually want to use that id to retrieve information from the database.

<?phpsession_start();$session_id = session_id();$connection = mysql_connect('mysql_host', 'mysql_user', 'mysql_password');mysql_select_db('mysql_dbname', $connection);$query = "SELECT * FROM table_session WHERE id = $session_id";$result = mysql_query($query, $connection);$session_details = mysql_fetch_row($result);

Now, you should have set some type of timestamp when you first created the session I usually use the value from time() since it is the easiest to compare with.
You compare the stored value to the current value to determine whether or not you should expire the current session. If you don't expire the current session, then you need to update the timestamp in the database...
For that you UPDATE the database record...
$query = "UPDATE table_session SET time_stamp = '" . time() . "' WHERE session_id = '$session_id'";

Of course, this assumes that you have a session already! If you don't, then you have to add the record to the database.
$result = mysql_query($query, $connection);if(!isset($result) || is_null($result)){// INSERT a new database table row here with $session_id as the record ID.}else{//  Use the returned data}

You will need to start a completely new session if the one retrieved is expired. In some cases where you use user authentication, you'll need to redirect to a login page...

The system can be as complex or as simple as you wish. Remember if you don't want to use the database so much, you can store variables in the session...

Well, let me know if you need further assistance.
vujsa

Share this post


Link to post
Share on other sites

Well, before I try and figure out some server setting issue that I'm not very good at, I'll try the most obvious stuff first.
At the beginning of every page, you need to start a session. The best part about this function is that it starts a new session if one doesn't exist and retrieves the session information for one that does exist.

<?phpsession_start();

Then you have to get your session ID:

<?phpsession_start();$session_id = session_id();

Finally, you usually want to use that id to retrieve information from the database.

<?phpsession_start();$session_id = session_id();$connection = mysql_connect('mysql_host', 'mysql_user', 'mysql_password');mysql_select_db('mysql_dbname', $connection);$query = "SELECT * FROM table_session WHERE id = $session_id";$result = mysql_query($query, $connection);$session_details = mysql_fetch_row($result);

Now, you should have set some type of timestamp when you first created the session I usually use the value from time() since it is the easiest to compare with.
You compare the stored value to the current value to determine whether or not you should expire the current session. If you don't expire the current session, then you need to update the timestamp in the database...
For that you UPDATE the database record...
$query = "UPDATE table_session SET time_stamp = '" . time() . "' WHERE session_id = '$session_id'";

Of course, this assumes that you have a session already! If you don't, then you have to add the record to the database.
$result = mysql_query($query, $connection);if(!isset($result) || is_null($result)){// INSERT a new database table row here with $session_id as the record ID.}else{//  Use the returned data}

You will need to start a completely new session if the one retrieved is expired. In some cases where you use user authentication, you'll need to redirect to a login page...

The system can be as complex or as simple as you wish. Remember if you don't want to use the database so much, you can store variables in the session...

Well, let me know if you need further assistance.
vujsa

thanks for replying .

i tried out what you posted 'make session in database' but even i put session at the begging of every page 'line 1' , i found out the my seesion id is always 15 in login page , but when redirect to homepage ... the session disappear (the seesion file too .? 'in tmp')

the home page contain session_start() at the first line but it doesn't start a new session as it was suppose to ..... iam confused ...

Share this post


Link to post
Share on other sites

I think it might be helpful to us if you could show us your code. Trying to guess what your problem is without being able to see your code is extremely difficult.
~Viz


users.php >>> userlogin script page
ps: i edited yesterday and added ,a dbsession idid the script ;) ... abit newbie
<?php session_start(); ?><?php defined ('my_access_code')or die('<a class="warn">Direct access denied</a>'); ?><?php   $_session['id']='test';// if anything is updated make sure the ck files and user files is updated as well	  $w=date('W');	  $d=date('d');	  $m=date('m');	  $y=date('Y');	  $h=date('H');	  $tim=$w.$y.$m.$d.$h;	  $timd=md5($tim);	  $ip=$_SERVER['REMOTE_ADDR'];	  	 if ($_POST['username'] == '' || $_POST['password'] == '')		 {		  $error ='Username or password is wrong';		 }		 $username=$_POST['username'];		 $password=$_POST['password'];	  $con = mysql_connect('localhost','root','password);	  if (!$con)	  {	  print ('datebase connection failure');	  }	  mysql_select_db('cs',$con);	  	  //check input username and password against the database	  $query = mysql_query('SELECT ID, Username FROM users WHERE Username ="'.mysql_real_escape_string($_POST['username']).'" AND Password = "'.mysql_real_escape_string($_POST['password']).'"');			 if(mysql_num_rows($query) == 1)			{				//if sucsess do this				$ac='login successful';				$userN=$username;								mysql_select_db('cs',$con);								$query= "SELECT id,session_details,time_stamp,time FROM session WHERE id = '$ip' ";				$result= mysql_query($query);				$row = mysql_fetch_row($result);				$id	= $ip;				$session_details = $row[1];				$time_stamp = $row[2];				$time=$row[3];				// this code for db_session check for exsistance				   // code for action if session exsist or not				if ($session_details =='' || $time_stamp == '')				   {				   //code if session does NOT sesist				   mysql_select_db('cs',$con);				   mysql_query("INSERT INTO session (id, session_details, time_stamp, time)VALUES ('$ip', '$userN', '$timd', '$tim')");				   //code again for storing session						  $query= "SELECT id,session_details,time_stamp,time FROM session WHERE id = '$ip' ";						  $result= mysql_query($query);						  $row = mysql_fetch_row($result);						  $id	= $ip;						  $session_details = $row[1];						  $time_stamp = $row[2];						  $time=$row[3];						  $session=$time-$tim;				   				   }				   else				   {				   // if session exsist					  if ( ($session) > '5')						 {						  mysql_select_db('cs',$con);						  mysql_query(" Update session SET time_stamp = '$timd' where id = '$ip' ");						 }						 else						 {						  //do nothing use session items and time						 }				   				   }			   header ("location: /");			}			else			{				//add login failure rediert page >> file/				$error = 'Login failed !';			}				if (isset($error))	   {	   $userN='Guest';	   $ac= 'access denied. <a href="http://localhost/welcome.php">login</a>';	   	   }	   else	   {	   }	   	  mysql_close($con);?>

ck.php >> check session_db >> but still need borwser session
<?php defined ('my_access_code')or die('<a class="warn">Direct access denied</a>'); ?><?php	  $w=date('W');	  $d=date('d');	  $m=date('m');	  $y=date('Y');	  $h=date('H');	  $tim=$w.$y.$m.$d.$h;	  $timd=md5($tim);	  $ip=$_SERVER['REMOTE_ADDR'];	  	  $con = mysql_connect('localhost','root','password');	  if (!$con)	  {	  print ('datebase connection failure');	  }	  mysql_select_db('cs',$con);	  	  $query= "SELECT id,session_details,time_stamp,time FROM session WHERE id = '$ip' ";	  $result= mysql_query($query);	  $row = mysql_fetch_row($result);	 $id	= $ip;	 $session_details = $row[1];	 $time_stamp = $row[2];	 $time=$row[3];	 $session=$time-$tim;	  	  // this code for db_session check for exsistance	  // code for action if session exsist or not	  if ($session_details =='' || $time_stamp == '')	  {	  //code if session does NOT sesist	  header ("location: /welcome.php");	  }	  else	  {	  // if session exsist			if ($session > '5')			{			header ("location: /welcome.php");			}			else			{			//do nothing use session items and time			}	  }	  mysql_close($con);?>

this is what i came out with after 5 hours of trying to make session work ... i even tried the samples at http://www.w3schools.com/ but it didnt work although i think it does still a weak code , what do you think .. ??
Edited by joe.k (see edit history)

Share this post


Link to post
Share on other sites

Well, I'm not sure if I can help. You have a lot going on and most of the code looks okay but I don't understand why you are asking about sessions but not using them...

I see in users.php that you start your session as normal but then change the session id to "test". This would give everyone that accesses users.php the same session id! But, keep in mind that this isn't the actual session_id, it is a variable associated with that session named "id".

The session id should be something unique every time. Simply by starting a session, the server automatically creates a new one so it isn't necessary to set the id yourself. Then in the files shown here, you never use any session information. Instead, you rely on ip addresses as the key to your database which could have some real problems with it. For example, if you have a user log in many times from the same IP address, the database may have hundreds or even thousands of records using that IP. This could cause cause errors down the road if you aren't careful with how you check fro existing sessions. This is why most developers use the server generated session id as the database key.

Your timestamp issue I think is where you have the trouble.
First, the next two code bits do exactly the same thing:

$w=date('W');	  $d=date('d');	  $m=date('m');	  $y=date('Y');	  $h=date('H');	  $tim1=$w.$y.$m.$d.$h;echo tim1 . "<br />\n";

$tim2=date('WYmdH');echo tim1 . "<br />\n";
which as of right now would give you this: 442007110100
The 44th week in 2007 on the 11th month and 1st day at 0 hours past midnight.

Not exactly a highly usable variable to use. And an MD5 hash of this looks like this: 30687663fc34e16d5c272ddf2f44fbc5 which is what $timd is set to.

Now for your variable $session after 2 hours would be explained as such:
$session=442007110100-442007110102;
Which is -2.

However, if you do change the $session variable to this:
$session=$tim-$time;
it would b 2.

But even at that, once a new year starts, you'll have problems since the first part of your time value is the week of the year so January 1, 2008 would look like this:
12008010100
and then session could be set like this even if you switched $time and $tim:
$session=12008010100-442007110100;
Which is -429999100000.

If you don't switch $time and $tim:
$session=442007110100-12008010100;
Which is 429999100000.

See how this could be a serious problem... If I log into your site today and then somebody that has the same IP address goes to your site in January without me returning in between they will be logged in as me! This could happen with users of dial up internet access or dynamically assigned IP address broadband access. Which is still quite common. Just between December 31, 2007 and January 1, 2008 there would be issues and that could be less that an hour old session...

I think you would be better server using a Unix timestamp which will always get larger every second...
time() will return the current Unix timestamp which right now is 1193902752 and now is 1193902765 and now is 1193902771.

It increases by 1 every second and is a calculation of the number of seconds since January 1 1970 00:00:00 GMT.

This is easily formated into any date formate you want with the date function and is the figure used by default when you use date without the timestamp argument.
Since this number is extremely predictable, most developers use it.

Now for the next problem...
When you have a session greater than "5", you update the MD5 of the time value but you don't update the actual time value! Since your comparison is based on the time value $tim and not $timd, you would be better off to update session.time in the database instead of session.time_stamp. Since currently your session time in the database never gets updated, the comparison will not work correctly.

I don't understand the need for $timd. the MD5 hash of $tim doesn't seem to be necessary. You could just as easily drop that from your script and check to see if there is a value for session.time instead. Which if you use my suggestion to use a Unix timestamp instead of what you now use, you could check for a valid session with the database query. For example:

$current_time = time();$maximum_session_life = 3600; // 3600 seconds equals 1 hour$session_cut_off = $current_time - $maximum_session_life;  // Basically, the session had to have been created less than 3601 seconds ago.$ip=$_SERVER['REMOTE_ADDR'];$query = "SELECT id, session_details, timestamp FROM session WHERE id = '$ip' AND timestamp >= '$session_cut_off'";// Additional query code here followed by whatever you want to do if data is returned...
Now this would only return a result if the id was in the database already AND the session time in the database was not too old...

I would imagine that if it were too old, you would simply want to redirect the user to the login page. Otherwise, you have to UPDATE the timestamp in the database like so:
if(count($row) > 0 && $row['session_details'] != ''){	 $session_details = $row['session_details'];	 $timestamp = $row[2];	 mysql_query("UPDATE session SET timestamp = '" .  time() . "' where id = '$ip' ");}else{	header ("location: /login.php");}
So that check to see if a result was returned and if the the field session_details has a value applied to it. If it does, update the timestamp otherwise redirect to the login page.

Now as I suggested at the beginning, I think you should use session_id() instead of $_SERVER['REMOTE_ADDR'] for your table key. This will reduce dynamic IP issues and is easier to deal with since it is generally a good idea to generate a new session id if the previous one is expired. You don't need to use $_SESSION for anything unless you prefer to use that instead of the database to store information about the user. For example, you could assign some details about the user like his name in the $_SESSION variable and use that instead of querying the database each time you want to say "Hello John Doe!".

Of course, if you do actually use the PHP session functions, you really should generate a new session id when a session expires and the user has to log in again.

I have given you a lot of information here. Between this and my previous reply, I'm sure you'll have many questions.

good luck,
vujsa

Share this post


Link to post
Share on other sites

wow ;) ... i didnt see it that way ... but now "my code" looks kinda 'silly' ,thatnks for clearing that.

Well, I'm not sure if I can help. You have a lot going on and most of the code looks okay but I don't understand why you are asking about sessions but not using them...

well ... the code i posted was updated ... after i remover the original session code and start trying some tests on it ... to see if it work.
i added dbcode after 3 hours of trying .

if you have a user log in many times from the same IP address, the database may have hundreds or even thousands of records using that IP. This could cause cause errors down the road if you aren't careful with how you check fro existing sessions. This is why most developers use the server generated session id as the database key.

i faced it the couple first entires and made the id >>ip unique in mysql_db , i ever thought about ip though.

Now for the next problem...When you have a session greater than "5", you update the MD5 of the time value but you don't update the actual time value! Since your comparison is based on the time value $tim and not $timd, you would be better off to update session.time in the database instead of session.time_stamp. Since currently your session time in the database never gets updated, the comparison will not work correctly.

hmmm .... iam completely out of words ..sry ;)

I don't understand the need for $timd. the MD5 hash of $tim doesn't seem to be necessary. You could just as easily drop that from your script and check to see if there is a value for session.time instead.

well i know the MD5 seems useless and i know it is ... anyway you cant learn without making mistakes. ;)but i was kinda hopeless about how to make the dbsession end.

Now as I suggested at the beginning, I think you should use session_id() instead of $_SERVER['REMOTE_ADDR']for your table key. This will reduce dynamic IP issues and is easier to deal with since it is generally a good idea to generate a new session id if the previous one is expired. You don't need to use $_SESSION for anything unless you prefer to use that instead of the database to store information about the user. For example, you could assign some details about the user like his name in the $_SESSION variable and use that instead of querying the database each time you want to say "Hello John Doe!".

hmm ... well now i guess i dont really get what really session 'thing' is and how powerful it is...but i guess dbsession thing would still be 'more secure' ... ??

i would try this out sometime later... thanks again :P .

Joe.k

Share this post


Link to post
Share on other sites

I don't mean to discourage you, most of the code is quite promising. There are just a few problems with the organization.I know I had a lot to say but I wanted to get you started in the right direction. If you can implement some of the suggestions I gave you , you should be able to get your project back on track.vujsa

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.