PHP 7.0.6 Released

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 external sources. The manual page on this topic includes many examples as well.

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 #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 #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 #3 In a 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 urlencode()d 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.

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 external sources. For example, $_GET['foo_x'].

Note:

Spaces in request variable names are converted to underscores.

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 array keys 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 External Sources.

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. I.e.

<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 = document.forms[0].elements['var[]'];
      

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.

Example #4 Generating Javascript with PHP

<?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();
}
?>

User Contributed Notes

martellare at hotmail dot com
13 years ago
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...

<?php
if ($string) { ... }  //false for $string == '' || $string == '0'
?>

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

<?php
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 'on'.  (That's for HTML in general, not PHP-specific).
martellare at hotmail dot com
13 years ago
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>

===================
davis at risingtiger dot net
12 years ago
I thought this might be useful to fellow PHP heads like myself out there.

I recently came across a need to transfer full fledged mutli-dimensional arrays from PHP to JAVASCRIPT.

So here it is and hopefuly good things come from it.

<?php
function phparray_jscript($array, $jsarray)
{
    function
loop_through($array,$dimen,$localarray)
    {
        foreach(
$array as $key => $value)
        {
            if(
is_array($value))
            {
                echo (
$localarray.$dimen."[\"$key\"] = new Array();\n");
               
loop_through($value,($dimen."[\"".$key."\"]"),$localarray);
            }
            else
            {
                echo (
$localarray.$dimen."[\"$key\"] = \"$value\";\n");
            }
        }
    }

    echo
"<script language=\"Javascript1.1\">\n";
    echo
"var $jsarray = new Array();\n";
   
loop_through($array,"",$jsarray);
    echo
"</script>";
}
?>
jetboy
10 years ago
While previous notes stating that square brackets in the name attribute are valid in HTML 4 are correct, according to this:

http://www.w3.org/TR/xhtml1/#C_8

the type of the name attribute has been changed in XHTML 1.0, meaning that square brackets in XHTML's name attribute are not valid.

Regardless, at the time of writing, the W3C's validator doesn't pick this up on a XHTML document.
ciprian dot stingu at gmail dot com
4 years ago
Using jquery is even easier to send (post) data between javascript and php

<?php
//make an asynchronous request
$.post("somefile.php", {"Param1" : true, "Param2" : 1, "Param3" : "some text"},
    function(
received_data)
    {
       
//do something with received data
       
$("#some_element").html(received_data);
    });

//make a post request
$.ajax({
   
type: "POST",
   
url: "somefile.php",
   
data: {"Param1" : true, "Param2" : 1, "Param3" : "some text"},
   
success: function(received_data)
        {
//do something with received data},
   
async: false
});
?>
bas at cipherware dot nospam dot com
13 years ago
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];
Jay
2 years ago
If you have a really large form, be sure to check your max_input_vars setting.  Your array[] will get truncated if it exceeds this.  http://www.php.net/manual/en/info.configuration.php#ini.max-input-vars
vlad at vkelman dot com
11 years ago
"4.  How do I get all the results from a select multiple HTML tag?"

I think that behavior of PHP which forces to use [] after a name of 'select' control with multiple attribute specified is very unfortunate. I understand it comes from old times when registerglobals = on was commonly used. But it creates incompatibility between PHP and ASP or other server-side scripting languages. The same HTML page with 'select' control cannot post to PHP and ASP server pages, because ASP does not require [] and automatically recognize when arrays are posted.
francesco
9 years ago
Another way to pass variables from JavaScript to PHP.

<script type="text/javascript" language="JavaScript">
<!--
function getScreenResolution()
{
    return document.form.ScreenResolution.value = screen.width + "x" + screen.height;
}
//-->
</script>
<form name="form" action="screen.php?show=ok" method="post" >
<input name="ScreenResolution" type="text" size="20" maxlength="9" />
<input name="show" type="submit" value="Submit" onclick="getScreenResolution()" />
</form>
<?php
   
echo $_POST['ScreenResolution'];
?>
tchibolecafe at freemail dot hu
9 years ago
Notes on question "1. What encoding/decoding do I need when I pass a value through a
form/URL?"

Doing an htmlspecialchars() when echoing a string as an HTML attribute value is not enough to make the string safe if you have accented (non-ASCII) characters in it. See http://www.w3.org/TR/REC-html40/appendix/notes.html#non-ascii-chars

The referred document recommends the following method to be used:

<?php
 
function fs_attr($path){
   
$retval='';
    for(
$i=0;$i<strlen($path);$i++){
     
$c=$path{$i};
      if(
ord($c)<128){
       
$retval.=$c;
      }else{
       
$retval.=urlencode(utf8_encode($c));
      }
    }
    return
htmlspecialchars($retval);
  }

 
$img_path='éöüä.jpg';
  echo
'<img src="'.fs_attr($img_path).'">';
?>

However, using utf8 encoding for path names is among others supported by Windows NT, above method fails when running for example on an Apache server on Linux.

A more fail safe way:

<?php
       
function fs_attr($path){
               
$retval='';
                for(
$i=0;$i<strlen($path);$i++){
                       
$c=$path{$i};
                        if(
ord($c)<128){
                               
$retval.=$c;
                        }else{
                                if(
PHP_OS==='WINNT')
                                       
$retval.=urlencode(utf8_encode($c));
                                else
                                       
$retval.=urlencode($c);
                        }
                }

                return
htmlspecialchars($retval);
        }
?>

There may be operating systems that want utf8 encoding, other than WINNT. Even this latter one won't work on those systems. I don't know about any possibility to determine immediately which encoding to be used on the file system of the server...
dreptack at op dot pl
11 years ago
I needed to post html form through image input element. But my problem was I had to use multiple image-buttons, each one for a single row of form table. Pressing the button was mention to tell script to delete this row from table and also (in the same request) save other data from the form table.
I wrote simple test-script to see what variable I should check for in a script:

I have a html document:

<form action="test.php" method="post">
<input type="image" name="varscalar" src="/images/no.gif" />
<input type="image" name="vararray[12]" src="/images/no.gif" />
</form>

And a php script:
<?php
 
if ($_POST) {
    echo
"post: <pre>"; print_r($_POST); echo '</pre>';
  }
?>

What I've discovered suprised me a lot!

After hitting on varscalar:

post:
Array
(
    [varscalar_x] => 6
    [varscalar_y] => 7
)

After hitting on upper right corner of vararray:

post:
Array
(
    [vararray] => Array
        (
            [12] => 2
        )

)

This mean when clicking on image-type input element, which name is an array, only y-part of a value is remembered.

The result is the same on: php 4.1.2 on Win98se, php 4.3.9-1 on linux
dmsuperman at comcast dot net
10 years ago
Here's a great way to pass JavaScript to PHP without even leaving the page:

<script type="text/javascript">
<!--

function xmlreq(){
  if(window.XMLHttpRequest){
    req = new XMLHttpRequest();
  }else if(window.ActiveXObject){
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  return(req);
}
function sendPhp(url){
  var req = xmlreq();
  req.onreadystatechange = stateHandler;
  req.open("GET", url, true);
  req.send(null);
}

sendPhp("updatedatabase.php?username=blah&displayname=whatever");
//-->
</script>
levinb at cs dot rpi dot edu
10 years ago
Well, I was working on this one project, on the assumption that I could get the values of all elements with the same name from an appropriately named array.  Well, I was *very* disappointed when I couldn't, so I made it so I did anyway.

The following script should convert the raw post data to a $_POST variable, with form data from SELECT elements and their ilk being transformed into an array.  It's heavily unoptimized, and I probably missed something, but it's relatively easy to read.  I welcome corrections.

<?php

if ($_POST) {
       
$postdata = file_get_contents('php://input');
       
       
$uglybugger = '/(?<=&)([^&=]+)(?:=([^&]*))/';
       
$matches = array();

       
preg_match_all($uglybugger, $postdata, $matches);

       
$_POST = array();

       
$match_count = count($matches[0]);
        for (
$i = 0; $i < $match_count; $i++) {
                if (!isset(
$_POST[$matches[1][$i]])) {
                       
$_POST[$matches[1][$i]] = array();
                }
               
$_POST[$matches[1][$i]][] = $matches[2][$i];
        }
       
$match_count = count($_POST);
        for (
$i = 0; $i < $match_count; $i++) {
                if (
count($_POST[$i]) == 1) {
                       
$_POST[$i] = $_POST[$i][0];
                }
        }
}

?>
Kenn White kennwhite dot nospam at hotmail dot com
12 years ago
Concerning XHTML Strict and array notation in forms, hopefully the information below will be useful:

If I have a form, name="f", and, say, an input text box, name="user_data[Password]", then in Javascript, to reference it I would do something like:
   
var foo = f['user_data[Password]'].value;

Now, say that in making the switch to XHTML strict, I decide to fully embrace standards compliance, and change my form to id="f", and the input text box to id="user_data[Password]"

Because these have id instead of name, I discover, that all my javascript validation routines just broke.  It seems that I have to now change all my js code to something like:

document.getElementById( 'user_data[Password]' ).focus();

I test this on all the major modern browsers, and it works well.  I'm thinking, Great!  Until I try to validate said page.  It turns out that the bracket characters are invalid in id attributes.  Ack!  So I read this thread:

http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=
UTF-8&th=78dea36fd65d9bbe&seekm=
pqx99.19%24006.13377%40news.ca.inter.net#link11
(link needs to be spliced, sorry)

What does this mean, I start asking myself?  Do I have to abandon my goal to migrate to XHTML strict?  Transitional seems so unsatisfying.  And why bother with a technique that seems to work on most browsers, if it's broken.  Alas, there is hope.

But then I read http://www.w3.org/TR/xhtml1/#h-4.10 carefully.  It says "name" is deprecated as a form attribute, but *NOT* specifically as an attribute in form *elements*.  It seems my solution is to use "id" for the form itself, but I can legally use "name" for the individual form components, such as select and text input boxes.  I get the impression that "name" as an attribute is eventually going away completely, but in extensive testing using the W3C validator, it passes "name" on form components, as long as "id" (or, strangely, nothing) is used to denote the form itself.

So for XHTML strict, the bottom line:
1. form, use id, not name
2. input, use id if you can, but if you need to use bracketed notation (for example, passing PHP arrays), i.e., foo[], you *MUST* use name for XHTML strict validation.

-kenn

kennwhite.nospam@hotmail.com
To Top