PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<Using PHPPHP and COM>
view the version of this page
Last updated: Thu, 21 Aug 2003

Chapter 32. PHP and HTML

PHP and HTML interact a lot: PHP can generate HTML, and HTML can pass information to PHP. Before reading these faqs, it's important you learn how to retrieve variables from outside of PHP. The manual page on this topic includes many examples as well. Pay close attention to what register_globals means to you too.

1. What encoding/decoding do I need when I pass a value through a form/URL?
2. I'm trying to use an <input type="image"> tag, but the $foo.x and $foo.y variables aren't available. $_GET['foo.x'] isn't existing either. Where are they?
3. How do I create arrays in a HTML <form>?
4. How do I get all the results from a select multiple HTML tag?
5. How can I pass a variable from Javascript to PHP?

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().

Example 32-1. 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.

Example 32-2. 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.

Example 32-3. 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 &amp;. 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.

2. I'm trying to use an <input type="image"> tag, but the $foo.x and $foo.y variables aren't available. $_GET['foo.x'] isn't existing either. Where are they?

When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:
<input type="image" src="image.gif" name="foo">
When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables: foo.x and foo.y.

Because foo.x and foo.y would make invalid variable names in PHP, they are automagically converted to foo_x and foo_y. That is, the periods are replaced with underscores. So, you'd access these variables like any other described within the section on retrieving variables from outside of PHP. For example, $_GET['foo_x'].

3. How do I create arrays in a HTML <form>?

To get your <form> result sent as an array to your PHP script you name the <input>, <select> or <textarea> elements like this:
<input name="MyArray[]">
<input name="MyArray[]">
<input name="MyArray[]">
<input name="MyArray[]">
Notice the square brackets after the variable name, that's what makes it an array. You can group the elements into different arrays by assigning the same name to different elements:
<input name="MyArray[]">
<input name="MyArray[]">
<input name="MyOtherArray[]">
<input name="MyOtherArray[]">
This produces two arrays, MyArray and MyOtherArray, that gets sent to the PHP script. It's also possible to assign specific keys to your arrays:
<input name="AnotherArray[]">
<input name="AnotherArray[]">
<input name="AnotherArray[email]">
<input name="AnotherArray[phone]">
The AnotherArray array will now contain the keys 0, 1, email and phone.

Note: Specifying an arrays key is optional in HTML. If you do not specify the keys, the array gets filled in the order the elements appear in the form. Our first example will contain keys 0, 1, 2 and 3.

See also Array Functions and Variables from outside PHP.

4. How do I get all the results from a select multiple HTML tag?

The select multiple tag in an HTML construct allows users to select multiple items from a list. These items are then passed to the action handler for the form. The problem is that they are all passed with the same widget name. ie.
<select name="var" multiple="yes">
Each selected option will arrive at the action handler as:
var=option1
var=option2
var=option3
Each option will overwrite the contents of the previous $var variable. The solution is to use PHP's "array from form element" feature. The following should be used:
<select name="var[]" multiple="yes">
This tells PHP to treat $var as an array and each assignment of a value to var[] adds an item to the array. The first item becomes $var[0], the next $var[1], etc. The count() function can be used to determine how many options were selected, and the sort() function can be used to sort the option array if necessary.

Note that if you are using JavaScript the [] on the element name might cause you problems when you try to refer to the element by name. Use it's numerical form element ID instead, or enclose the variable name in single quotes and use that as the index to the elements array, for example:
variable = documents.forms[0].elements['var[]'];

5. How can I pass a variable from Javascript to PHP?

Since Javascript is (usually) a client-side technology, and PHP is (usually) a server-side technology, and since HTTP is a "stateless" protocol, the two languages cannot directly share variables.

It is, however, possible to pass variables between the two. One way of accomplishing this is to generate Javascript code with PHP, and have the browser refresh itself, passing specific variables back to the PHP script. The example below shows precisely how to do this -- it allows PHP code to capture screen height and width, something that is normally only possible on the client side.

<?php
if (isset($_GET['width']) AND isset($_GET['height'])) {
  // output the geometry variables
  echo "Screen width is: ". $_GET['width'] ."<br />\n";
  echo "Screen height is: ". $_GET['height'] ."<br />\n";
} else {
  // pass the geometry variables
  // (preserve the original query string
  //   -- post variables will need to handled differently)

  echo "<script language='javascript'>\n";
  echo "  location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
            . "&width=\" + screen.width + \"&height=\" + screen.height;\n";
  echo "</script>\n";
  exit();
}
?>



add a note add a note User Contributed Notes
PHP and HTML
email at njschedules dot com
19-Oct-2003 11:13
If you try to include an XHTML document in a PHP document, you may be including this:

<?xml version="1.0" encoding="iso-8859-1"?>

which would, of course, be read as PHP code. To avoid this problem, use:

echo "<?xml version=
Warning: Unexpected character in input: '\' (ASCII=92) state=1 in /home/php/include/layout.inc on line 21
"1.0\" encoding=\"iso-8859-1\"?".">"?>

Hope I can save you from those nasty warning messages :)
04-Oct-2003 05:25
Responding to the suggestion for using this line:

<form onSubmit="selection.name=selection.name + '[]'">

This did not work for me.  I had to make a function makeArray:

function makeArray(selectBox)
{
selectBox.name=selectBox.name + "[]";
}

Then, in the submit button, add this:

onClick='makeArray(this.form.selection)'

I couldn't get anything else to work.

--Rafi
jasonpb at bellsouth dot net
30-Sep-2003 01:29
Another good way for passing javascript to php without having to have a page reload is to use an img tag.

(example)
Add this where you want to collect the vars from
This can also be a .html page
<script language="javascript">
<!--//
// Define variables
if (navigator.appname != 'Netscape') {color= "color="+screen.colorDepth+"&";}
else {color = "color="+screen.pixelDepth+"&";}
avail = "avail="+screen.availwidth+"x"+screen.availheight+"&";
res = "res="+screen.width+"x"+screen.height;
isize = '" width="1" height="1" border="0"';
// Generate img tag
img = '<img name="img"
src="javascript.php?'+color+avail+res+isize+'">';
//Print it to browser
document.write(img);
//-->
</script>

Now you have the javascript vars passed along to the javascript.php page, all thats left is to add a couple lines of php code to gather the info up.

(example)
<?
// Get the vars from the javascript
$res $_GET['res'];
$avail_res $_GET['avail'];
$color_depth $_GET['color'];
// Do something with the info
echo "You Screen's Resolution is $res, Your Available Screen Resolution is $avail_res, and the Color Depth on your screen is $color_depth.";
?>
Thats it!!
Hope it may help someone!
matt at itk-network dot com
28-Apr-2003 06:20
I dont know if this was hinted at earlier, but you can (sort of) pass values from javascript to PHP:

<form method="get" name="f">
<input type="hidden" name="somevalue" />
// Rest of form

<input type="submit" name="Submit" />
</form>

<script type="text/javascript">
<!--
      var myvar = "some value";
      document.f.somevalue.value = myvar;
//-->
</script>

Now when you submit the form, the javascript value "myvar" will be in the hidden form, and sent to PHP.
martellare at hotmail dot com
16-Mar-2003 04:28
I do not think you are right about not being able to specify something for the value attribute, but I can see where you would have thought it would fail:

A fair warning about testing to see if a variable exists...
when it comes to strings, the values '' and '0' are interpreted as false when tested this way...

if ($string) { ... }  //false for $string == ? || $string == ??br />
The best practice for testing to see if you received a variable from the form (which in the case of a checkbox, only happens when it is checked) is to test using this...

if ( isSet($string) ) { ... } //true if and only if the variable is set

The function tests to see if the variable has been set, regardless of its contents.

By the way, if anyone's curious, when you do make a checkbox without specifying the value attribute, the value sent from the form for that checkbox becomes n?  (That's for HTML in general, not PHP-specific).
Ronan dot Minguy at wanadoo dot fr
06-Mar-2003 11:53
USING CHECKBOXES IN A FORM

If you're using a checkbox in a form and want test if the checkbox was checked, you must not specify any value in the checkbox input, otherwise it won't work.
Id est  :

echo "<input type=\"checkbox\" name=\"cb\">

will work
you can then test after submitting the form like this

if ($cb)
{
//what to do if the box was checked
}
else
{
//what to do if the box wasn't checked
}
 
but
echo "<input type=\"checkbox\" name\"cb\" value\"$cb\">
won't work. If your using the same "if" instruction than above, it will be always false.

Believe me I spend hours wondering why it wasn't working!
Ronan
josh at NO chatgris SPAM dot com
15-Jan-2003 06:18
For those of you familiar with ASP or apache aprea_request_params_as_string, this function should be very welcome to you to turn things like

<input type="hidden" name="selected_category_ids[]" value="1">
<input type="hidden" name="selected_category_ids[]" value="4">
<input type="hidden" name="selected_category_ids[]" value="5">
<input type="hidden" name="selected_category_ids[]" value="6">
<input type="hidden" name="selected_category_ids[]" value="7">

into

1, 4, 5, 6, 7

To use it, pass the name from html into this function, WITH the []'s (you can remove the log_func from this function if you want).

Basically, this functgion checks for a [] at the end of the string.  If it's there, it converts it to a comma delimited string, if not, it returns the value as normal.

function getBlindFormData( $form_name ) {
      if ( !is_string( $form_name ) ) {
        $this->{$this->log_func} ( "File: %s. Line: %d. \$form_name is NOT a string.", __FILE__, __LINE__ );
    }
   
    $offs = strlen( $form_name ) - 2;
    if ( strpos ( $form_name, "[]", $offs ) === $offs ) {
        $form_name = substr( $form_name, 0, $offs );
        $isarray = 1;
    } else {
        $isarray = 0;
    }
   
    if ( isset( $_GET[$form_name] ) ) {
        $request = $_GET[$form_name];
    }
   
    if ( isset( $_POST[$form_name] ) ) {
        $request = $_POST[$form_name];
    }

    $ret = NULL;
    if ( isset( $request ) ) {
        if ( $isarray ) {
        $ret = $request[0];
        for ( $i = 1; $i < count( $request ); $i++ ) {
          $ret .= ", ".$request[$i];
        }
      } else {
        $ret = $request;
      }
    }

    return $ret;
  }

Usage could be as follows

To select a comma delimited list of values.

$sql = sprintf( "DELETE FROM categories\n"
                      .    "  WHERE category_id IN ( %s );\n"

                      , $wrapper->getRequiredFormData( "selected_category_ids[]" ) );

or just $wrapper->getOptionalFormData( "category_id" ); for retrieval of a normal http variable.

Any questions, problems, bugs you find in this email me at the abvoe email address. (remove the NO before chatgris and the SPAM after chatgris etc.)
river att clacks dot org
28-Dec-2002 04:41
Having defined Another Array, as in the example above, to access the element [email] directly from the $_POST superglobal,  the syntax is

$value = $_POST[AnotherArray][email];

and not

$value = $_POST[AnotherArray[email]];

as newcomers to PHP might expect.  Once I worked out the correct syntax it works fine!

Hope that saves someone some time

River~~
martellare at hotmail dot com
27-Nov-2002 03:25
A JavaScript Note: Using element indexes to reference form elements can cause problems when you want to add new elements to your form; it can shift the indexes of the elements that are already there.

For example, You've got an array of checkboxes that exist at the beginning of a form:
===================

<FORM>
    <INPUT type="checkbox" name="fruits[]" value="apple">apple
    <INPUT type="checkbox" name="fruits[]" value="orange">orange
    <INPUT type="checkbox" name="fruits[]" value="banana">banana
</FORM>

===================
... These elements could be referenced in JavaScript like so:
===================

<SCRIPT language="JavaScript" type="text/javascript">
<!--
    var index = 0; //could be 1 or 2 as well
    alert(document.forms[0].elements[index]);
//-->
</SCRIPT>

===================
However, if you added a new textbox before these elements, the checkboxes indexes become 1 - 3 instead of 0 - 2;  That can mess up what ever code you create depending on those indexes.

Instead, try referencing your html arrays in JavaScript this way.  I know it works in Netscape 4 & IE 6, I hope it to some extent is universal...
===================

<SCRIPT language="JavaScript" type="text/javascript">
<!--
    var message = "";
    for (var i = 0; i < document.forms[0].elements['fruits[]'].length; i++)
    {
        message += "events[" + i + "]: " + document.forms[0].elements['fruits[]'][i].value + "\n";
    }
    alert(message);
//-->
</SCRIPT>

===================
karatidt at web dot de
18-Nov-2002 04:57
this code selects all elements with javascript
and hands them over to an array in php *sorry my english is not good*

javascript:

<script language="JavaScript">
<!--
function SelectAll(combo)
 {
   for (var i=0;i<combo.options.length;i++)
    {
      combo.options[i].selected=true;
    }
 }
//-->
</script>

html code:
<form name="form" action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<select name="auswahl[]" size="10" multiple>
<option value="bill@ms.com">Bill Gates</option>
<option value="bill@unemployed.com">Bill Clinton</option>
<option value="bart@brat.com">Bart Simpson</option>
<option value="oj@free.com">OJ Simpson</option>
<option value="j@nbc.com">Jay Leno</option>
</select>

<input type="submit" name="submit1"  value="OK" onclick="SelectAll(document.form.elements['auswahl[]'])">
</form>

php code:

$auswahl = $_POST["auswahl"];
       
foreach ($auswahl as $value)
    {
        echo $value."<br>";
    }
bas at cipherware dot nospam dot com
17-Oct-2002 11:52
Ad 3. "How do I create arrays in a HTML <form>?":

You may have problems to access form elements, which have [] in their name, from JavaScript. The following syntax works in IE and Mozilla (Netscape).

index = 0;
theForm = document.forms[0];
theTextField = theForm['elementName[]'][index];
cwestnea at SPAMindiana dot edu
17-Jul-2002 12:44
I've found that a neat trick is to do:

<form onSubmit="selection.name=selection.name + '[]'">

That way you can still do form.selection, instead of form.elements['selection[]'] and still capture multiple variables.
dark dot cyclo at skynet dot be
05-Jul-2002 04:58
To send all values from the multiple select, you must all select with a thing like this (javascript) :

<form OnSubmit="
for (i=0; i<SelectArray.length; i++){
  SelectArray.options[i].selected = true;
}
">
hjncom at hjncom dot net
25-May-2002 05:30
I think '[' and ']' are valid characters for name attributes.

http://www.w3.org/TR/html401/interact/forms.html#h-17.4
-> InputType of 'name' attribute is 'CDATA'(not 'NAME' type)

http://www.w3.org/TR/html401/types.html#h-6.2
-> about CDATA('name' attribute is not 'NAME' type!)
...CDATA is a sequence of characters from the document character set and may include character entities...

http://www.w3.org/TR/html401/sgml/entities.html
--> about character entity references in HTML 4
([ - &#91, ] - &#93)
cricel at hotmail dot com
24-May-2002 10:01
You can also use this to create multidimensional arrays:

<input type="text" name="bob[]">
<input type="text" name="bob[1][]">

makes an array of:
bob[0] = some text
bob[1] = an array
bob[1][0] = some text

Fun stuff, very helpful in submitting an entire form and putting all the data into a single array rather than naming each element....

<Using PHPPHP and COM>
 Last updated: Thu, 21 Aug 2003
show source | credits | sitemap | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: http://php.mirrors.ilisys.com.au/
Last updated: Sat 01 Nov 2003 04:13:36 EST EST