The Old Way: Accessing Global Variables
The code shown in Listing 2 treats the forms values as globals:
Listing 2. Form values as globals
|
The resulting Web page shows the submitted values:
|
(As you'll see in a minute, there's no value for Contact because that box wasn't checked.)
The notation in Listing 2 is certainly convenient, but it is only available if the PHP directive register_globals
is set to on
.
Prior to version 4.2, this was the default, and many PHP developers may
even be unaware that there's an issue. Starting with version 4.2,
however, the default setting for register_globals
is off
, in which case this notation doesn't work because the variables are never created and initialized with the appropriate values.
You can, however, use other ways to initialize these variables. The first is to change the value of register_globals
.
Many developers who work on shared servers don't have the option to
change this value for the entire server, but behavior can be changed
for a particular site. If you have access to the .htaccess
file, you can turn on register_globals
by adding the directive:
|
Because of the uncertainty in whether this feature is available, developers are advised that it's better not to use or rely on this method of acquiring variables. So what options do you have?
If your system is running version 4.1 or higher, another option is to selectively register sets of globals using import_request_variables()
. You can use this function to import get, post, and cookie values, and to add a prefix to each, if desired. For example:
|
Here, both get and post values are imported -- use c
to import cookie values -- and because p
follows g
, post values will override get values of the same name.
But what if, like many developers, you're not running version 4.1 or higher?
View Using HTML forms with PHP Discussion
Page: 1 2 3 4 5 6 Next Page: Accessing Form Value Collections