Page 1 of 6

help with understanding sessions and practical/correct usage

Posted: Mon Sep 25, 2006 11:30 am
by Obadiah
i would have said so in the title guys but heres your official warning this is gonna be a long one...many appologies to the admins if i posted this question in the wrong forum

in many of my here ive been trying to find a way to connect to a database via a single user on a site pull up information based on his login so he can veiw his own personal files...

the more i snooped around reading post, replying, and asking via new posts the unifying thought of sessions connected my inquiries to the inquiries of others, so this weekend i looked up the subject in the php manual and came across the following code snippet...it seems as though the example is spit up into fuctions to be
used througout coding of the page...i understand that much...but alot of it i just dont get...i have broken the
snippet up by functions in order to ask the questions im not understanding

Code: Select all

<?
 class Session
 {
  function _makeid()
  {
   $time    = time();
   $ip      = $_SERVER["REMOTE_ADDR"];
   $agent  = $_SERVER["HTTP_USER_AGENT"];
   $md5 = md5($time.$ip.$agent);
   setcookie("SClass", $md5);
   return($md5);
  }
i understand that its making an id obviously by the title...lol...but how could i use a id already determined by a
login screen...like say that this code is on the page the user gets after he logs in...how would this pertain to
specifically him vs anyone else? what exactly does this code do?

Code: Select all

function getid()
  {
   $md5 = $_COOKIE['SClass'];
   return($md5);
  }

  function start()
  {
   $id = $this->getid();
   if (!$id) { $id = $this->_makeid(); }
  }

  function _getfile()
  {
   $file = $this->getid();
   $file .= ".ssn";
   $file = "[--PATH-TO-SESSION-FOLDER--]".$file;
   return($file);
  }
ok....here again its making the id then its getting the id...understood(mostly i think :?...lol)...in the getID
function $md5 is set to a cookie then its value being returned

i really dont understand the start function at all but if i were to take a guess it looks like the $ID that was made in the previous function is being set to the current one...if not then make it that way(once again guessing)

waht is the get file function for? what is it supposed to do? in the manual before the posted snippet
the author wrote
Before use, you must replace "[--PATH-TO-SESSION-FOLDER--]" with the path to where sessions should be stored. Make sure to set the proper permissions for that folder
why and how would you use a folder if the information on the page is all being pulled from the database?

the rest of the code i didnt include because i was hoping to get an explanation for this first

Posted: Mon Sep 25, 2006 3:07 pm
by thomas777neo
Your request is pretty vague and confusing...

You want to have a user log into your site, have his credentials checked in a database, then have an identifier recorded in a session so that he can only retrieve his stuff?

Posted: Mon Sep 25, 2006 3:25 pm
by Obadiah
yea...kinda like if you went to a online banking site....you would logon and afterwards it would say,
hello frodo(or whatever your user name is) and below that it would give you your accout balace, and if
another person were to log on to the same banking site it would give them the same layout only it would display their name and their information...im thinking im gonna have to use user sessions for it

Posted: Mon Sep 25, 2006 3:33 pm
by Luke
php's native sessions would definately be able to handle that... along with a data storage medium such as mysql or just plain text files. You may find a full list of them here:
http://us3.php.net/session
And just in case that isn't clear enough, I'll give a quick-and-dirty explaination. We'll start with session information... ids and mysql and all that aside... let's talk about what sessions do...

What a session does, is create a unique id for each user who visits the page. PHP tries to store this id on the client's machine by way of a cookie. If the user doesn't have cookies enabled, then it will store the session id in the url (this is why you will often see ?PHPSESSID=blablabla on a lot of sites). It then associates this id with a file on the server where it will store all session data.

Does that make sense?

Posted: Mon Sep 25, 2006 3:41 pm
by thomas777neo
Using sessions in my opinion is a good idea.

But, what have you done already? Do you have a database setup? Do you know how to connect to it and retrieve values? What php version are you using?

A straight forward example is to create a login screen, that posts your username and password to the database.

If you find a valid user for the detail provided, you would then allow them into your site and then store the user' id (usually the primary key in your database) and name etc

Quick usage of sessions:

Code: Select all

/*
    * receive username and password
    * check if in database
    * if found, create session
*/

// create session part

session_start(); // simply start the session

$_SESSION["name"] = $db_name_found;

/*
    * this would create a session and add the variable name to it with the value retrieved from the database.
    * all that you need to do to get the $_SESSION["name"] value is to use the session_start() function on the      page that you need to use it on then simply echo $_SESSION["name"] and it would show the name you got from the database
*/
EDIT: too late, sort of

Posted: Tue Sep 26, 2006 2:29 am
by chakhar86
if the native session handler of PHP is that good,why whould some site or application (e.g. PHPbb) use other method to implement the session.

And I would like to ask, if two or more users connect simultanously, will this session changed?
And if the user/client close his/her browser without 'logging out', how will u erase the session in the '/PHPSESSION' path?
Thx

Posted: Tue Sep 26, 2006 2:33 am
by thomas777neo
The session created will be different for the concurrent users.

The session also has an expiry time in the php.ini, which should take care of the deletion

Posted: Tue Sep 26, 2006 8:19 am
by Obadiah
@spacegoat= understood perfectly...lol...if only the books i had would put it in 'lamens' terms like
that....the book im reading doesnt really cover sessions all that well...sessions are exactly what
im wanting to use for this project....however its the step by step process that has me intimidated, it great
to have a place i can ask all my questions if i run into a problem along creation or during hw :)

@thomas777= ive gotton everything besides the seesion stuff done and you can view the code for it
here its the forth post...its the login...and thats as far as i gotten so far...

i dont understand enough to begin writing the sessions for it besides what you guys have
explained to me so far...and im actually about to go test some of it out via "wing-in it" thanx guys
i greatly appriciate all your help thus far....please continue to post back :)

Posted: Tue Sep 26, 2006 9:18 am
by Rovas
Here is a quite good tutorial http://www.goodphptutorials.com/track/79 and even better one here
http://devzone.zend.com/node/view/id/646 .
Read them and come back with questions.

Posted: Tue Sep 26, 2006 10:16 am
by Obadiah
so, in order for this to work...i have tostart the session on the login page?

i thought that it was possible to start the session on the page the user goes to after it allows him
access, kinda like the user logs in then hes sent to a page with something like this as code

Code: Select all

<?php
// create session part 

session_start(); // simply start the session 
$_GET ['user_name']
$_SESSION["name"] = $db_name_found;

$display_block="welcome $user_name. to the secret page";
?>
<html>
<head>
<title>Secret Page</title>
</head>
<body>
<?php echo $display_block; ?>
</body>
</html>
assuming that i didnt break hundreds of php protocal right there by wing-in it :wink:, is something
like this possible?

Posted: Wed Sep 27, 2006 8:07 am
by Obadiah
will it work if i start writing the session on the "secret page"(referring to the page the user is directed to
after he logs in) or should i rewrite my login....also...i was looking at this
thomas777neo wrote:

Code: Select all

$_SESSION["name"] = $db_name_found;
/*
    * this would create a session and add the variable name to it with the value retrieved from the database.
    * all that you need to do to get the $_SESSION["name"] value is to use the session_start() function on the      page that you need to use it on then simply echo $_SESSION["name"] and it would show the name you got from the database
*/
assuming that it is possible for me to do this on the "secret page" how does php know what database to
access?

Posted: Wed Sep 27, 2006 2:35 pm
by Obadiah
it was suggested that i try the tutorial herehttp://www.goodphptutorials.com/track/79 in the
hopes of thinking maybe there isnt anyway for me to begin the session on the page the user goes to
after they log in, so i made up my mind to rewrite my login....now i have tons of errors....lol.... and now im
more confused then when i started....the writer jumped from place to place and im not sure whether or not
i have the right code in the right files....all im wanting to do is call the session function outside of the login page
is that possible?? can anyone help me out with this?

Posted: Thu Sep 28, 2006 1:30 pm
by Obadiah
anyone? :cry:

Posted: Thu Sep 28, 2006 2:39 pm
by volka
Obadiah wrote:so, in order for this to work...i have tostart the session on the login page?
Yes. You want to store the information that the user has been authenticated, at this point you need the session running.
Obadiah wrote:will it work if i start writing the session on the "secret page"(referring to the page the user is directed to
after he logs in) or should i rewrite my login....also...i was looking at this
How "secret" can this page be if the browser is redirected to it? What if someone types that url in the browser's location bar? No, that's the wrong place to initialize the session.

Posted: Thu Sep 28, 2006 3:48 pm
by Obadiah
with that said....can something like this be done(please correct my "wing-in it" if not)

Code: Select all

switch (@$_POST['Button']) 
  { 
    case "Login": 
      $cxn = Connect_to_db("Vars.inc"); 
      $sql = "SELECT user_name FROM $table_name 
              WHERE user_name='$_POST[fusername]'"; 
      $result = mysqli_query($cxn,$sql) 
                  or die("Couldn't execute query 1"); 
      $num = mysqli_num_rows($result); 
      if($num == 1) 
      { 
         $sql = "SELECT user_name FROM $table_name 
                 WHERE user_name='$_POST[fusername]' 
                 AND password=md5('$_POST[fpassword]')"; 
         $result2 = mysqli_query($cxn,$sql) 
                   or die("Couldn't execute query 2.");  
         $row = mysqli_fetch_assoc($result2); 
         if($row) 
         {
           session_start();
           $_SESSION["name"] = $db_name_found; 
           $_SESSION['auth']="yes"; 
           $_SESSION['logname'] = $_POST['fusername']; 
           header("Location: $next_program"); 
         }
now if your answer is no....then if so is it because it needs to be in a sort of a if-then-else kinda setup....how would i do this?