Welcome Guest ( Log In | Register )




                Web Hosting Guide

 
Reply to this topicNew Topic
Php Session Problem
joe.k
post Oct 27 2007, 07:34 PM
Post #1


Member [ Level 2 ]
Group Icon

Group: Members
Posts: 65
Joined: 21-December 06
From: Jordan
Member No.: 18,611


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 smile.gif.

Joe.k
Go to the top of the page
 
+Quote Post
vujsa
post Oct 27 2007, 11:19 PM
Post #2


Absolute Newbie
Group Icon

Group: Admin
Posts: 888
Joined: 20-February 05
From: Indianapolis, Indiana, USA (Midwest)
Member No.: 2,714
myCENTs:35.43


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.
CODE
<?php
session_start();


Then you have to get your session ID:

CODE
<?php
session_start();
$session_id = session_id();


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

CODE
<?php
session_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...
CODE
$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.
CODE
$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
Go to the top of the page
 
+Quote Post
joe.k
post Oct 28 2007, 06:53 AM
Post #3


Member [ Level 2 ]
Group Icon

Group: Members
Posts: 65
Joined: 21-December 06
From: Jordan
Member No.: 18,611


QUOTE(vujsa @ Oct 28 2007, 02:19 AM) [snapback]112860[/snapback]
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.
CODE
<?php
session_start();


Then you have to get your session ID:

CODE
<?php
session_start();
$session_id = session_id();


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

CODE
<?php
session_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...
CODE
$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.
CODE
$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 ...
Go to the top of the page
 
+Quote Post
vizskywalker
post Oct 29 2007, 09:32 PM
Post #4


Techno-Necromancer
Group Icon

Group: Members
Posts: 1,018
Joined: 13-January 05
From: The Net
Member No.: 2,127


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
Go to the top of the page
 
+Quote Post
joe.k
post Oct 31 2007, 08:22 PM
Post #5


Member [ Level 2 ]
Group Icon

Group: Members
Posts: 65
Joined: 21-December 06
From: Jordan
Member No.: 18,611


QUOTE(vizskywalker @ Oct 29 2007, 11:32 PM) [snapback]112923[/snapback]
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 smile.gif ... abit newbie
CODE
<?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
CODE
<?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 www.w3schools.com but it didnt work although i think it does still a weak code , what do you think .. ??

This post has been edited by joe.k: Nov 1 2007, 09:54 AM
Go to the top of the page
 
+Quote Post
vujsa
post Nov 1 2007, 08:20 AM
Post #6


Absolute Newbie
Group Icon

Group: Admin
Posts: 888
Joined: 20-February 05
From: Indianapolis, Indiana, USA (Midwest)
Member No.: 2,714
myCENTs:35.43


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:
CODE
$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";


CODE
$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:
CODE
$session=442007110100-442007110102;

Which is -2.

However, if you do change the $session variable to this:
CODE
$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:
CODE
$session=12008010100-442007110100;

Which is -429999100000.

If you don't switch $time and $tim:
CODE
$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:

CODE
$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:
CODE
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
Go to the top of the page
 
+Quote Post
joe.k
post Nov 1 2007, 09:45 AM
Post #7


Member [ Level 2 ]
Group Icon

Group: Members
Posts: 65
Joined: 21-December 06
From: Jordan
Member No.: 18,611


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

QUOTE

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 .

QUOTE

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.

QUOTE

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 huh.gif

QUOTE

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. smile.gif
but i was kinda hopeless about how to make the dbsession end.

QUOTE

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 smile.gif .

Joe.k
Go to the top of the page
 
+Quote Post
vujsa
post Nov 1 2007, 11:24 AM
Post #8


Absolute Newbie
Group Icon

Group: Admin
Posts: 888
Joined: 20-February 05
From: Indianapolis, Indiana, USA (Midwest)
Member No.: 2,714
myCENTs:35.43


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
Go to the top of the page
 
+Quote Post

Reply to this topicNew Topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Collapse

> Similar Topics

    Topic Title Replies Topic Starter Views Last Action
No New Posts   7 tansqrx 1,920 30th October 2009 - 12:39 PM
Last post by: iG-gurjeet singh
No new   68 BooZker 35,327 25th October 2009 - 03:33 PM
Last post by: iG-Jon
No New Posts   9 Logan Deathbringer 1,798 13th October 2009 - 06:56 PM
Last post by: iG-Doulos
No New Posts   3 Eggie 1,253 2nd October 2009 - 12:45 AM
Last post by: iG-candy
No New Posts   16 Chesso 1,701 28th September 2009 - 10:59 PM
Last post by: iG-Carol
No New Posts   9 mpinsky 2,898 21st September 2009 - 07:15 AM
Last post by: iGuest
No New Posts   5 al421552 802 18th September 2009 - 10:44 AM
Last post by: iG-djay4me
No New Posts   10 takerraj 154 17th September 2009 - 04:25 AM
Last post by: xboxrulz
No New Posts   16 victorhu 6,400 13th September 2009 - 10:02 PM
Last post by: iG-Happy Unlocker User
No New Posts   5 surfermac 211 11th September 2009 - 09:06 PM
Last post by: Curt200518
No new 22 Ronel 5,369 10th September 2009 - 12:25 AM
Last post by: iG-Icetea
No New Posts 9 doudou 3,392 6th September 2009 - 08:30 PM
Last post by: iGuest
No New Posts   14 hoplite 4,942 11th August 2009 - 11:07 AM
Last post by: iG-Amirelle
No New Posts   8 musichere 2,022 11th August 2009 - 03:01 AM
Last post by: iG-TheMaker
No New Posts   17 ikenalleenik 3,377 30th July 2009 - 12:54 PM
Last post by: iG-Frank


Web Hosting Powered by ComputingHost.com.