10.8 PHP and HTML
10 FAQ : Foire Aux Questions
Manuel PHP
->
What encoding/decoding do I need when I pass a value through a form/URL?
.
I'm trying to use an <input type="image"> tag, but
the . How do I create arrays in a HTML <form>? .
How do I get all the results from a select multiple HTML tag?
.
How can I pass a variable from Javascript to PHP?
|
10.8.1
What encoding/decoding do I need when I pass a value through a form/URL?
There are several stages for which encoding is important. Assuming that
you have a
string
$data
, which contains
the string you want to pass on in a non-encoded way, these are the
relevant stages:
-
HTML interpretation. In order to specify a random string, you
must
include it in double quotes, and
htmlspecialchars
the whole value.
-
URL: A URL consists of several parts. If you want your data to be
interpreted as one item, you
must
encode it with
urlencode
.
A hidden HTML form element |
<?php echo "<input type='hidden' value='" . htmlspecialchars($data) . "'>\n"; ?>
|
Note |
It is wrong to
urlencode
$data
, because it's the browsers responsibility to
urlencode
the data. All popular browsers do that
correctly. Note that this will happen regardless of the method (i.e.,
GET or POST). You'll only notice this in case of GET request though,
because POST requests are usually hidden.
|
Data to be edited by the user |
<?php echo "<textarea name='mydata'>\n"; echo htmlspecialchars($data)."\n"; echo "</textarea>"; ?>
|
Note |
The data is shown in the browser as intended, because the browser will
interpret the HTML escaped symbols.
Upon submitting, either via GET or POST, the data will be urlencoded
by the browser for transferring, and directly urldecoded by PHP. So in
the end, you don't need to do any urlencoding/urldecoding yourself,
everything is handled automagically.
|
In an URL |
<?php echo "<a href='" . htmlspecialchars("/nextpage.php?stage=23&data=" . urlencode($data)) . "'>\n"; ?>
|
Note |
In fact you are faking a HTML GET request, therefore it's necessary to
manually
urlencode
the data.
|
Note |
You need to
htmlspecialchars
the whole URL, because the
URL occurs as value of an HTML-attribute. In this case, the browser
will first un-
htmlspecialchars
the value, and then pass
the URL on. PHP will understand the URL correctly, because you
urlencoded
the data.
You'll notice that the
&
in the URL is replaced
by
&
. Although most browsers will recover
if you forget this, this isn't always possible. So even if your URL is
not dynamic, you
need
to
htmlspecialchars
the URL.
|
|