CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 11 of 11
  1. #1
    Join Date
    Aug 2006
    Location
    Dallas, TX
    Posts
    47

    [RESOLVED] Sessions

    Every time i try to pass variables in the session data to the next form nothing gets transferred. The session gets created but the variables are not created and no values are assigned to them. Any help would be appreciated

    PHP Code:
    if(!$db){
      
    trigger_error("Could not perform the specified query. Please contact an admin!",E_USER_ERROR);
    }else{
      
    $sql "SELECT * FROM users WHERE UserName='$usernme'";
      
    $resultmysql_query($sql);
      while (
    $myrow mysql_fetch_array($result)) {
        if (
    $myrow['UserName']===$usernme && $myrow['Password']===$password){
          if(
    $myrow['Verified']==="1"){
            
    session_start();
            
    session_register('user','pass');
            
    $user=$myrow["UserName"];
            
    $pass=$myrow["Password"];
            
    header("Location: /igl/user.php?$PHPSESSID");
          }else{
            
    $error="Sorry, Your account has not yet been activated!";
          }
        }else{
          
    $error="Sorry, Username or Password invalid!";
        }
      } 

    Last edited by cypher5783; August 31st, 2006 at 09:12 PM. Reason: organization

  2. #2
    Join Date
    May 2002
    Posts
    10,943

    Re: Sessions

    You need to organize your code. People will not have the desire to help if you don't make it simpler on them.

    1. Don't use === you only need ==.
    2. You misspelled $username in the $sql... line
    3. You haven't declared any session variables.

    Below is your code organized. Now you need to declare session variables or else session variables don't exist.

    PHP Code:
    session_start();
    $_SESSION['variablename'] = 'variablevalue'
    PHP Code:
    if(!$db){
      
    trigger_error("Could not perform the specified query. Please contact an admin!"E_USER_ERROR);
    }
    else{
      
    $sql "SELECT * FROM users WHERE UserName='$username'";
      
    $resultmysql_query($sql);
      while (
    $myrow mysql_fetch_array($result)) {
        if (
    $myrow['UserName']==$usernme && $myrow['Password']==$password){
          if(
    $myrow['Verified']=="1"){
            
    session_start();
            
    session_register('user','pass');
            
    $user=$myrow["UserName"];
            
    $pass=$myrow["Password"];
            
    header("Location: /igl/user.php?$PHPSESSID");
          }
          else{
            
    $error="Sorry, Your account has not yet been activated!";
          }
        }
        else{
          
    $error="Sorry, Username or Password invalid!";
        }
      }

    If the post was helpful...Rate it! Remember to use [code] or [php] tags.

  3. #3
    Join Date
    Aug 2006
    Posts
    69

    Re: Sessions

    One thing, the session needs to be created absolutely first thing in the script. Before ANYTHING else happens, start the session.

    One thing I did when writing alot of PHP scripts for web development, I wrote a session handling class which is pretty handy to use. It takes care of some of the tedious junk you need to do when starting and dealing with sessions.

    Here's the class code:
    PHP Code:
    <?php
      
    class session {
        function 
    session($sesName 'PHPSESSID'$sesPath '/tmp') {
          
    session_name($sesName);
          
    session_save_path($sesPath);

          if(!
    is_dir($sesPath)) {
            
    mkdir($sesPath);
            if(!
    is_dir($sesPath)) {
              echo
                   
    "Unable to access temporary session storage!<BR>\n<BR>\n",
                   
    "This is a serious error which cannot be worked around.<BR>\n",
                   
    "Until the problem is resolved, this script will terminate here.<BR>\n",
                   
    "Thank you and have a nice day.<BR>\n";
              exit;
            }
          }

          
    session_start();
        }

        function 
    keep() {
          
    $argc func_num_args();
          
    $argv func_get_args();
          foreach(
    array_keys($_SESSION) as $key) {
            if(
    array_search($key$argv) === false) {
              
    $this->resetParam($key);
            }
          }
        }
          
        function 
    disallow() {
          
    $argc func_num_args();
          
    $argv func_get_args();  // only passed key name will be kept
      
          
    foreach(array($_GET$_POST) as $formdata) {
            foreach(
    $formdata as $key => $value) {
              if(!
    array_search($key$argv)) {
                if(!isset(
    $_SESSION[$key]) || $_SESSION[$key] != $formdata[$key]) { 
                  
    $_SESSION[$key] = $formdata[$key];
                }
              }
            }
          }
        }

        function 
    resetParam() {
          
    $argc func_num_args();
          
    $argv func_get_args();
          foreach(
    $argv as $value) {
            
    $_SESSION[$value] = false;
            
    session_unregister($value);
            unset(
    $_SESSION[$value]);
          }
        }

        function 
    val($key) {
          return 
    $_SESSION[$key];
        }

        function 
    set($key$value) {
          if(
    $value == '' || $value === false || !isset($value)) {
            
    $this->resetParam($key);
          }
          else {
            
    $_SESSION[$key] = $value;
          }
        }
      }
    ?>
    To use it, there are three steps. Create the class, determine what to maintain, and then enable it by setting disallows.

    To create the class at the first of the php script, optionally giving a session ID and storage path for the ID:

    PHP Code:
    $ses  = new session();
    //  or  something like
    //$ses = new session('processform', '/tmp/shoppingcart'); 
    Second, set up a listing of form params that you want to continuously maintain in the session:

    PHP Code:
    $ses->keep('username''userid''loggedin'); 
    Keep in mind that these params are always kept. You probably don't want to maintain the users password in the session.. ocne they log in, you can set the 'loggedin' session var (as an example).

    And the last thing to do is, set session form params that cannot be passed in from the form. Meaning, suppose you're using the 'loggedin' param to say whether or not the user has already logged in.. well, you don't want the user to be able to pass in a GET param called 'loggedin', because they could bypass the login that way.. so, you set 'loggedin' in the disallow list:

    PHP Code:
      $ses->disallow('loggedin'); 
    This means that your script can set it, and since it's in the 'keep' list, it will be persistent in the session, but the form itself cannot set it.

    The disallow MUST be called. This method does the actual form->session copying.

    And your session is ready to use! Any script using this will maintain the same session variables. The class comes with the following session methods:

    PHP Code:
    //  sets which form params are persistent in the session
    $ses->keep();

    //  sets which params cannot be passed in by the form,
    // also copies form params to session. must be called
    $ses->disallow();

    //  resets (zeroes out) any param in the list
    $ses->resetParam('username''id''formcolor');

    //  returns the value of the session variable given
    print $ses->val('username');

    //  sets a new value of the session variable
    $ses->set('username'$returnedUserName); 
    And that's all there is to using it.

    Hopefully even if you don't want to use it, it will give you some ideas and help you get your code working.

  4. #4
    Join Date
    May 2002
    Posts
    10,943

    Re: Sessions

    @thelinuxduck

    Please be more on target with your posts. And remember that if you write a lot, the user is less inclined to read it all.
    If the post was helpful...Rate it! Remember to use [code] or [php] tags.

  5. #5
    Join Date
    Aug 2006
    Posts
    69

    Re: Sessions

    Quote Originally Posted by peejavery
    @thelinuxduck
    Please be more on target with your posts. And remember that if you write a lot, the user is less inclined to read it all.
    With all due respect, my post was on target.

    The user wanted to know a way to fix his problems with session variables and handling, and I provided a robust solution. I didn't provide a way to fix his specific code, but provided examples of successful handling of sessions. This is a very appropriate means of teaching and explanation.

    As for longer posts, I'd rather someone took the time to explain something and gave examples of code than a short and potentially cryptic response. When I make replies, I try to provide details as to how to use something, and provide code examples through-out the post. Longer posts need to be broken up with examples so that they are not tedious to read.

    The only thing I should not have done was inlined the session class. I should have linked it..

    Again, all respect intended.

    TLD

  6. #6
    Join Date
    May 2002
    Posts
    10,943

    Re: Sessions

    Quote Originally Posted by thelinuxduck
    With all due respect, my post was on target.
    Respectfully as well, your post was all about sessions and your opinion of how to work directly with sessions. You did not address cypher5783's code nor his problem. You posted a whole new meaning to sessions.

    Sorry about the disagreement, but respectfully disagree with you. Now, let's stay on the original topic and wait for cypher5783 to respond.
    If the post was helpful...Rate it! Remember to use [code] or [php] tags.

  7. #7
    Join Date
    Aug 2006
    Location
    Dallas, TX
    Posts
    47

    Question Re: Sessions

    Personally I like of your methods but that isn't the issue. It was my understanding that using:
    PHP Code:
    session_register('user','pass'); 
    would register the variables in the session and then
    PHP Code:
    $user=$myrow["UserName"]; 
    $pass=$myrow["Password"]; 
    would assign those variables values.

    I also tried changing it to pee's suggestion of using
    PHP Code:
    $_SESSION['variablename'] = 'variablevalue'
    which also didn't pass the variable to the next form. Is my problem in the way the session is being transferred to the next page?
    PHP Code:
    header("Location: /igl/user.php?$PHPSESSID"); 
    or is there something i need to do on the next page to load the session into it? Sessions are still new to me.

  8. #8
    Join Date
    May 2002
    Posts
    10,943

    Re: Sessions

    How are you grabbing the session variables on the next page? Sounds to me like that is an issue. Try the following short example and see what happens.

    main.php
    PHP Code:
    <?php
    session_start
    ();
    $_SESSION['test'] = "I hope this works!";
    header("Location: newpage.php");
    ?>
    newpage.php
    PHP Code:
    <?php
    session_start
    ();
    echo 
    $_SESSION['test'];
    ?>
    If the post was helpful...Rate it! Remember to use [code] or [php] tags.

  9. #9
    Join Date
    Aug 2006
    Location
    Dallas, TX
    Posts
    47

    Re: Sessions

    thx pee after this last post i found the issue. But now a new issue still with sessions. When the user logs out I destroy the session.
    PHP Code:
    if($sessid){
      
    session_destroy();
      echo 
    "You signed out successfully. Please click <a href=\"login.php\">Here to login again.</a>";

    but if the user then logs in again without closing browser. the session doesn't get any variables passed like it's trying to reuse a session id that's no longer valid but doesn't give an error. any thoughts?

  10. #10
    Join Date
    Aug 2006
    Location
    Dallas, TX
    Posts
    47

    Re: Sessions

    please disreguard. Found my problem with that as well. thx guys you've been a big help. site should be all downhill from here. *hopefully*

  11. #11
    Join Date
    May 2002
    Posts
    10,943

    Re: [RESOLVED] Sessions

    Glad all is working. Good luck with the rest.
    If the post was helpful...Rate it! Remember to use [code] or [php] tags.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured