Developer Forums | About Us | Site Map
Search  
HOME > TUTORIALS > SERVER SIDE CODING > PHP TUTORIALS > USING HTML FORMS WITH PHP


Sponsors





Useful Lists

Web Host
site hosted by netplex

Online Manuals

Using HTML forms with PHP
By Nicholas Chase - 2003-12-12 Page:  1 2 3 4 5 6

The Old Way: Accessing Global Variables

The code shown in Listing 2 treats the forms values as globals:

Listing 2. Form values as globals


<?php

echo "Ship = ".$ship;
echo "<br />";
echo "Tripdate = ".$tripdate;
echo "<br />";
echo "Exploration = ".$exploration;

echo "<br />";
echo "Contact = ".$contact;

?>

The resulting Web page shows the submitted values:


Ship = Midnight Runner
Tripdate = 12-15-2433
Exploration = yes
Contact =

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



php_flag register_globals on

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:


<?php

import_request_variables(gp, "formval_");

echo "Ship = ".$formval_ship;
echo "<br />";
echo "Tripdate = ".$formval_tripdate;

echo "<br />";
echo "Exploration = ".$formval_exploration;
echo "<br />";
echo "Contact = ".$formval_contact;

?>

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

First published by IBM developerWorks


Copyright 2004-2024 GrindingGears.com. All rights reserved.
Article copyright and all rights retained by the author.