| home / programming / php_forms / 1 | [previous] [next] |
|
|

The value in a text field (and in a password field and in
a hidden field, as well) is provided in its value attribute.
However, the data there must be properly encoded
with htmlspecialchars() to get rid of dangerous characters
such as ‘ or < or >.The code snippet in the preceding
code expects the form to be submitted back to
itself; thus, it extracts the current value of the text field
from $_POST (it would work analogously with $_GET).
If you want to use a default value for this form element, you just have to provide this default value instead of the empty string in the PHP code:

Another possibility is to prefill form values from cookies.
This is quite useful when users enter their data into
a form several times. So, when they visit a form on the
site a couple of days later, the old data can be retrieved
from the cookie.Yes, just one cookie since only 20
cookies per domain are allowed.We use an array for
that, of course. However, only strings are allowed
as cookie values, so the use of serialize() and
unserialize() is required.
$_GET or $_POST contains a
current value for this field, this value is used (specific
versions of the function exist for $_GET and $_POST
because only one of these two methods is normally
used at a time). Otherwise, the script looks in $_COOKIE
for an associated value. If nothing is found, an empty
string is returned.

Now, prefilling the form value is easy: Because
getFormDataGET() and getFormDataPOST() always return
anything—including an empty string—the return
value can be directly used in the text field’s value
attribute.


With multiline text fields, almost the same approach as
with single-line text fields and password fields can be
used.The only difference is the location where to put
the prefill value: It belongs between <textarea> and
</textarea>, as shown in the code.


Using the combined cookie/GET or cookie/POST
approach, the code simplifies a bit.

| home / programming / php_forms / 1 | [previous] [next] |
Created: March 27, 2003
Revised: January 16, 2006
URL: http://webreference.com/programming/php_forms/1