Problem with session variables?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Nicole

    Problem with session variables?

    Hi

    I'm trying to use a function to set a session variable. I have three files:

    The first file has:

    <?php session_start() ; // This connects to the existing session
    ?>
    <html>
    <head>
    <title>Untitl ed Document</title>
    </head>
    <body>
    <p> <a href="functions .php?FuncToExec =countrySelectU S">Execute countrySelect
    function</a></p>
    </body>
    </html>


    I then have a functions.php file:

    <?php session_start() ;
    session_registe r ("country");
    $HTTP_SESSION_V ARS ["country"] = $country;
    $country="UK"; //default
    ?>
    <?php
    if($FuncToExec == "countrySelectU S"){
    countrySelectUS ();
    }?>
    <html>
    <head>
    <meta http-equiv="refresh" content="12; URL=thiscountry .php">
    <title>Untitl ed Document</title>
    </head>
    <body>
    <?php
    function countrySelectUS () {
    $country="US";
    echo "new country is: " . $country;
    }
    ?>
    </body>
    </html>


    And finally thiscountry.php :

    <?php session_start() ; ?>
    <html>
    <head>
    <title>Untitl ed Document</title>
    </head>

    <body>
    You are in
    <?php echo $country ?>

    </body>
    </html>


    However when i click on the link in the first page, the functions.php page
    displays saying
    'new country is: US'

    but the final page gets displayed with:
    'You are in UK'

    The function is obvioulsy being run, but for some reason the change in value
    for country isnt being 'stored' as part of the session, only the value
    assigned when its created.

    Thats not how I was understanding they should work

    Can anyone explain what I have done wrong?

    Many thanks for any help given

    N


  • Ian B

    #2
    Re: Problem with session variables?

    Try

    if($_GET['FuncToExec'] == "countrySelectU S"){

    Comment

    • Ian B

      #3
      Re: Problem with session variables?

      First reply seems to have got lost....

      Use $_SESSION['country'] not $country in countrySelectUS ()

      $country in countrySelectUS () is local

      Alternatively, use
      global $country;

      Comment

      • Ian B

        #4
        Re: Problem with session variables?

        "the change in value for country isnt being 'stored' as part of the
        session" because you are saving it in the local (to the function) var
        $country which goes out of scope when the function ends

        Either use

        $_SESSION['country']

        or use

        "global $country"

        The former is preferable for readability and still leaves you with
        $country to use locally.

        Ian

        Comment

        • Nicole

          #5
          Re: Problem with session variables?

          Hiya

          I'm confused now as i thought

          $HTTP_SESSION_V ARS ["country"] = $country;

          meant that i could refer to the session variable as $country ?

          Also I get 'uk' from $country in the 'thiscountry.ph p' which i thought
          suggested that $country was refering to the session variable?

          However, I did what you suggested and changed functions so it now looks
          like:

          <?php session_start() ;
          session_registe r ("country"); // Create a session variable called name
          $HTTP_SESSION_V ARS ["country"] = $country;
          $country="UK";
          ?>
          <?php
          if($FuncToExec == "countrySelectU S"){
          countrySelectUS ();
          }?>

          <html>
          <head>
          <meta http-equiv="refresh" content="12; URL=thiscountry .php">
          <title>Untitl ed Document</title>
          <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
          </head>

          <body>
          <?php
          function countrySelectUS () {
          $_session['country']="US";
          echo "new country is: " .$_session['country'];
          }
          ?>
          </body>
          </html>

          However, I still get the same problem, I click on the link, functions.php
          displays showing 'new country is: US' and then I move automatically to
          thiscountry.php where it says 'You are in UK'

          which I dont understand :(

          N



          "Ian B" <ianbambury@gma il.com> wrote in message
          news:1130232597 .162435.299180@ g14g2000cwa.goo glegroups.com.. .[color=blue]
          > "the change in value for country isnt being 'stored' as part of the
          > session" because you are saving it in the local (to the function) var
          > $country which goes out of scope when the function ends
          >
          > Either use
          >
          > $_SESSION['country']
          >
          > or use
          >
          > "global $country"
          >
          > The former is preferable for readability and still leaves you with
          > $country to use locally.
          >
          > Ian
          >[/color]


          Comment

          • Hilarion

            #6
            Re: Problem with session variables?

            > I'm confused now as i thought[color=blue]
            >
            > $HTTP_SESSION_V ARS ["country"] = $country;
            >
            > meant that i could refer to the session variable as $country ?[/color]

            Nope. It means that you store value of $country variable under "country"
            name. You are also using here an old way of accessing session values
            (you are using $HTTP_SESSION_V ARS instead of $_SESSION).

            What is making $country refer to session is session_registe r function
            (which will NOT work if register_global s is turned off, which means
            most PHP servers).

            [color=blue]
            > Also I get 'uk' from $country in the 'thiscountry.ph p' which i thought
            > suggested that $country was refering to the session variable?[/color]

            It's a result of using session_registe r.

            [color=blue]
            > However, I did what you suggested and changed functions so it now looks
            > like:
            >
            > <?php session_start() ;
            > session_registe r ("country"); // Create a session variable called name
            > $HTTP_SESSION_V ARS ["country"] = $country;
            > $country="UK";
            > ?>
            > <?php
            > if($FuncToExec == "countrySelectU S"){
            > countrySelectUS ();
            > }?>
            >
            > <html>
            > <head>
            > <meta http-equiv="refresh" content="12; URL=thiscountry .php">
            > <title>Untitl ed Document</title>
            > <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
            > </head>
            >
            > <body>
            > <?php
            > function countrySelectUS () {
            > $_session['country']="US";[/color]

            This should be $_SESSION, not $_session. Variable names are case sensitive
            in PHP.

            [color=blue]
            > echo "new country is: " .$_session['country'];
            > }
            > ?>
            > </body>
            > </html>
            >
            > However, I still get the same problem, I click on the link, functions.php
            > displays showing 'new country is: US' and then I move automatically to
            > thiscountry.php where it says 'You are in UK'
            >
            > which I dont understand :([/color]

            It's because you used $_session variable, which is not the one you
            should.

            In general you should not use session_registe r but use $_SESSION array:


            <?php
            session_start() ;
            if (!isset($_SESSI ON['country'])
            {
            $_SESSION['country'] = 'UK';
            }

            if ($FuncToExec == 'countrySelectU S')
            {
            countrySelectUS ();
            }
            ?>
            <html>
            <head>
            <meta http-equiv="refresh" content="12; URL=thiscountry .php">
            <title>Untitl ed Document</title>
            <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
            </head>
            <body>
            <?php
            function countrySelectUS ()
            {
            $_SESSION['country'] = 'US';
            echo 'new country is: ' .$_SESSION['country'];
            }
            ?>
            </body>
            </html>

            I also do not understand why do you use such a complicated way of selecting
            countries. I would use something like this (one single file, where
            first part could be an include file included in every page):

            <?php
            error_reporting ( E_ALL );
            session_start() ;
            $countries = array( 'US', 'UK', 'PL' );
            if (isset( $_GET['country'] ) && in_array( $_GET['country'], $countries ))
            {
            $_SESSION['country'] = $_GET['country'];
            }
            else if (!isset($_SESSI ON['country'])
            {
            $_SESSION['country'] = 'UK';
            }
            ?>
            <html>
            <head>
            <title>Untitl ed Document</title>
            </head>

            <body>
            You are in
            <?php
            echo htmlspecialchar s( $_SESSION['country'] );
            ?>.<br />
            <br />
            Select country:
            <?php
            $link = $_SERVER['PHP_SELF'] . '?country=';
            $output = array();
            foreach( $country in $countries )
            {
            if ($country == $_SESSION['country'])
            {
            $output[] = '<b>' . htmlspecialchar s( $country ) . '</b>';
            }
            else
            {
            $output[] = '<a href="' . htmlspecialchar s( $link . $country ) . '">'
            . htmlspecialchar s( $country )
            . '</a>';
            }
            }
            echo implode( ', ', $output );
            ?>
            </body>
            </html>


            Hilarion

            Comment

            • Ian B

              #7
              Re: Problem with session variables?

              Hi Nicole,

              Yep you would get the same result because $_session is different from
              $_SESSION

              PHP variables are case sensitive

              As Hilarion said, you are using the old way of accessing variables.

              It is better to use the format $_SESSION['country'] for a number of
              reasons:

              * Having started a session with session_start() , you don't need to
              register any variable
              * It is independent of "register_globa ls" - whatever this setting is,
              you can always access $_SESSION['country']
              * register_global s = On is dangerous because it can mask or be masked
              by other variable
              * register_global s = On is dangerous because users can add variables
              to the query string and override stuff you thought was safe

              Think of it like this:

              * The first time a browser window calls session_start() , PHP goes off
              to find the session variables, finds none and gives you an empty
              $_SESSION array.

              * You can amend $_SESSION vars by assigning values to them. If they
              don't exist, they will be created.

              * PHP makes sure that these values are always saved

              * The next time that the same browser window calls session_start() , PHP
              creates the $_SESSION array and loads the existing values, so you have
              them back again.

              $_SESSION vars are available from within functions

              Nice and simple if you leave it at that.

              With register_global s = On, PHP creates an $var for every
              $_SESSION['var']. These are not available within function unless you
              use "global $var", so "$var m= 27;" within a function will create a
              local $var which will mask your session $var

              Setting $HTTP_SESSION_V ARS ["country"] = $country; means that anything
              you do to $country will be done to $HTTP_SESSION_V ARS ["country"] since
              they are now one and the same (I think)

              BUT...$country still has the same scope that any other $var has, so if
              you do $HTTP_SESSION_V ARS ["country"] = $country; within a function,
              $country disappears when the function ends ($HTTP_SESSION_ VARS
              ["country"] remains, though)


              Simple answer: Stick with $_SESSION['country'] - it's simpler, obvious,
              and a lot safer

              Ian

              Comment

              • Hilarion

                #8
                Re: Problem with session variables?

                > * register_global s = On is dangerous because it can mask or be masked[color=blue]
                > by other variable[/color]

                I'm not sure if I understand you. If you are about variables scope,
                then it has not much to do with register_global s. Regardless of it
                being on or off all variables have same scope. register_global s only
                makes some variables automatically set to values from environment
                ($_ENV, $_SERVER) and from request ($_REQUEST or rather directly
                $_GET, $_POST and $_COOKIE).

                [color=blue]
                > * register_global s = On is dangerous because users can add variables
                > to the query string and override stuff you thought was safe[/color]

                Yes. Having that in mind it's also possible to write scripts that are
                safe even when register_global s is on, but if it's off then still
                writing unsecure scripts is possible (for example register_global s
                does not affect most SQL injection attacks).

                [color=blue]
                > With register_global s = On, PHP creates an $var for every
                > $_SESSION['var'].[/color]

                As far as I know it does not. It does it (by reference) when calling
                session_registe r.

                [color=blue]
                > These are not available within function unless you
                > use "global $var", so "$var m= 27;" within a function will create a
                > local $var which will mask your session $var[/color]

                Yes, because it's a global variable and all scope rules apply.

                [color=blue]
                > Setting $HTTP_SESSION_V ARS ["country"] = $country; means that anything
                > you do to $country will be done to $HTTP_SESSION_V ARS ["country"] since
                > they are now one and the same (I think)[/color]

                Nope. This only assigns value of $country variable to the session
                values array. It does not bind the variable as a session variable.
                session_registe r does the bind. Additionaly $HTTP_SESSION_V ARS is
                only a global variable (scope rules apply), not a superglobal
                as $_SESSION (available in all scopes).

                [color=blue]
                > BUT...$country still has the same scope that any other $var has, so if
                > you do $HTTP_SESSION_V ARS ["country"] = $country; within a function,
                > $country disappears when the function ends ($HTTP_SESSION_ VARS
                > ["country"] remains, though)[/color]

                As above. This assignment does nothing to global variables including
                session values because $HTTP_SESSION_V ARS and $country variables
                are local to the function.

                [color=blue]
                > Simple answer: Stick with $_SESSION['country'] - it's simpler, obvious,
                > and a lot safer[/color]

                I agree.


                Hilarion

                Comment

                Working...