Monday, December 4, 2006

Access Form Variables

An aim of using php for you may be processing html forms. its easy to access form variables in php. i wont write a sample html form code here. i suppose you already have an html form where each input has a name value. There are general 3 ways of accessing form variables in php. Lets suppose that you have an input field in your form named as input_var :

$input_var //short style
$_POST['input_var'] //middle style
$HTTP_POST_VARS['input_var'] //long style

the short style is valid only if the register_globals configuration is on. since php version 4.2.0 this configuration is off as default. this style is not recommended.

middle style is the recommended style that is valid since php version 4.1.0

long style was portable in the past but now requires the register_long_arrays configuration.

i always use the middle style. it is easy, not confusing and also portable. if you dont want to access your form variable like this everywhere needed in your code then you can just assign it to another variable (with the form name generally) and use it freely as you need.

$input_var = $_POST['input_var'];
// lets use our form variable for output
echo $input_var;

Concatenate Strings

when you need printing more than one strings where there may be variables or other things between them, it would be annoying to write a new statement to echo all the parts. php has a nice way of doing this for you, string concatenating
let me show you an example:

echo "you have " . $msg_num . "messages!" ;

the . operator is the string concatenation operator and is very useful for situations like this. ( i left spaces after and before '.' operators to make them more visible. this is not needed in fact. )
you could also write the statement above like that without string concatenating :

echo "you have $msg_num messages!" ;

this will give an output like:

you have 3 messages!

depending on the variable $msg_num .
be careful that you can do this only inside double quotes. if you use a statement like that:

echo 'you have $msg_num messages! ' ;

you 'll get html output exactly as in the quotes:

you have $msg_num messages!

there should be a value instead of $msg_num here so we should use double quotes for this statement. single quotes give output without changing.