473,608 Members | 2,457 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
Oct 25 '05 #1
7 2030
Try

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

Oct 25 '05 #2
First reply seems to have got lost....

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

$country in countrySelectUS () is local

Alternatively, use
global $country;

Oct 25 '05 #3
"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

Oct 25 '05 #4
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" <ia********@gma il.com> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
"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

Oct 25 '05 #5
> I'm confused now as i thought

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

meant that i could refer to the session variable as $country ?
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).

Also I get 'uk' from $country in the 'thiscountry.ph p' which i thought
suggested that $country was refering to the session variable?
It's a result of using session_registe r.

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";
This should be $_SESSION, not $_session. Variable names are case sensitive
in PHP.

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 :(


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
Oct 25 '05 #6
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

Oct 25 '05 #7
> * register_global s = On is dangerous because it can mask or be masked
by other variable
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).

* register_global s = On is dangerous because users can add variables
to the query string and override stuff you thought was safe
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).

With register_global s = On, PHP creates an $var for every
$_SESSION['var'].
As far as I know it does not. It does it (by reference) when calling
session_registe r.

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
Yes, because it's a global variable and all scope rules apply.

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)
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).

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)
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.

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


I agree.
Hilarion
Oct 25 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

18
8308
by: ZoombyWoof | last post by:
Hi. Im very new to php, and I have a problem here that I cant find the solution for. I have problems with session variables, I want some variables to maintain their value between different php script that is being called. I have read the online manual, and here is an example from it that doesnt work for me, it illustrates very well my problem. File 1, index.php <?php // index.php
13
23295
by: Mimi | last post by:
Hello, I am having trouble using the session vars in PHP 4.3.9 OS: Win XP Prof Web Server IIS (is local and there are no links to other servers from the web pages I work on) Browser: IE 6.0 The problem I am having is that each time I reload the same PHP page, I get
1
3996
by: Jonathan Chong | last post by:
I have problem with AOL browser (IE and Netscape are OK) accessing my Web site after putting up a load balancer that will go to W1 or W2. The problem does not happen when there is only Web server and no load balancer installed. The problem is on the checking of the session timeout function. This function will check if the session variable's value is missing. If it is missing, it will direct to time out page.
3
2811
by: Gary | last post by:
I am having a strange problem that I cannot solve. I have an asp page that I use for a user to login and gain access to other pages. When the user logs in I set a couple of session variables like Session("UserType") = "Sales". Then based on the Session("UserType") I use response.redirect to take the user to a specific page. The logic and response.redirect works fine on a Win2k server but when I move the page to a server running Win2003 the...
7
2304
by: Adam Short | last post by:
I'm having all sorts of problems with Sessions, I've been using them for years with out a hitch, all of a sudden the last 6 - 12 months since getting our new Win2003 server it's all gone shakey!!! Our development server started life as an NT4 machine and has been simply upgraded from one operating system to the next, it is now a cross, NT4 Server, Win2000 Server, Win2003 server. All development sites work fine and under heavy stress. ...
5
4470
by: Newton | last post by:
Hi, I got here the following problem. I am programming web application for examing students. After student will log on I need to keep his ID, Privileges, Login, Password for manipulating with other functions. All these information I will keep by Session = "2" Session = "Student"
6
3246
by: Scott Zabolotzky | last post by:
I'm trying to pass a custom object back and forth between forms. This custom object is pulled into the app using an external reference to an assembly DLL that was given to me by a co-worker. A query-string flag is used to indicate to the page whether it should instantiate a new instance of the object or access an existing instance from the calling page. On the both pages I have a property of the page which is an instance of this custom...
8
3351
by: Ashish | last post by:
Incase the problem got bogged down reposting... Hi Gregory, I think I didnt make myself much clear. The problem is: 1. I have one ASP.NET application (no classic asp) and it has a main page (i.e. kinda SDI main window) that contains an IFrame. 2. I load different ASPX pages (that belong to the same ASP.NET project) in
0
1445
by: Alexander Widera | last post by:
hello all, i have a problem ... like I already discussed in the thread "session empty" I have the following problem: I created a completely new web... i added 2 files: sessiontest1.aspx:
3
2855
by: stclaus | last post by:
Hi, I'm currently experiencing a problem using sessions under php 4.4.2. I store variables and objects inside session variables, and all works well under php 5.x, but when I upload those pages to my hosting (tiscali italia business) the whole site and session variables seem to work at the beginning, but after a variable number of request (sometimes the second, sometimes the fifteenth page requested) all the site get stuck, every request...
0
8059
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8470
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8145
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8330
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6011
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3960
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2474
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1589
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1328
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.