PHP Australia Conference 2015

外部から来る変数

HTML フォーム (GET と POST)

フォームが PHP スクリプトに投稿された時、フォームから渡された全て の変数は PHP により自動的にスクリプトから使用可能となります。 この情報にアクセスする手段は複数あります。例を以下に示します。

例1 簡単なHTMLフォーム

<form action="foo.php" method="post">
    Name:  <input type="text" name="username" /><br />
    Email: <input type="text" name="email" /><br />
    <input type="submit" name="submit" value="Submit me!" />
</form>

PHP 5.4.0 以降、HTML フォームからデータにアクセスする方法は二種類だけとなります。 現在使える方法を、以下にまとめます。

例2 簡単なPOST HTMLフォームからのデータにアクセスする

<?php 
echo $_POST['username'];
echo 
$_REQUEST['username'];
?>

古いバージョンの PHP では、これら以外にもユーザーの入力にアクセスする方法がありました。 それを以下にまとめます。詳細は、最後の変更履歴を参照ください。

例3 ユーザーの入力にアクセスするための古い方法

<?php
// 注意:これらの方法は、現在はサポートされていません。
// 現在使えるのは、先ほどの方法だけです。

// import_request_variables() を使う方法:この関数は PHP 5.4.0 で削除されました
   
import_request_variables('p''p_');
   echo 
$p_username;

// 長い形式の定義済み変数を使う方法:この変数は PHP 5.4.0 で削除されました
   
echo $HTTP_POST_VARS['username'];

// register_globals を使う方法:この機能は PHP 5.4.0 で削除されました
   
echo $username;
?>

GETフォームを使用した場合も同じですが、かわりに適当な定義済みの GET変数を使用するところが異なります。 GETは、QUERY_STRING (URLの'?'の後の情報)にも代入されます。 例えば、 http://www.example.com/test.php?id=3には、 $_GET['id']によりアクセス可能なGETデータ が含まれます。 $_REQUEST も参照ください。

注意:

変数名のドットやスペースはアンダースコアに変換されます。 たとえば <input name="a.b" />$_REQUEST["a_b"] となります。

PHPではフォーム変数のコンテキスト内で配列が使用可能です(FAQの関連箇所も参照してください)。 例えば、関連する変数をグループ化したり、select inputで複数の値を 取得するといったことが可能です。フォームを同じスクリプトに投稿し、 投稿したデータを表示する例を示します。

例4 より複雑なフォーム変数

<?php
if ($_POST) {
    echo '<pre>';
    echo htmlspecialchars(print_r($_POST, true));
    echo '</pre>';
}
?>
<form action="" method="post">
    Name:  <input type="text" name="personal[name]" /><br />
    Email: <input type="text" name="personal[email]" /><br />
    Beer: <br />
    <select multiple name="beer[]">
        <option value="warthog">Warthog</option>
        <option value="guinness">Guinness</option>
        <option value="stuttgarter">Stuttgarter Schwabenbräu</option>
    </select><br />
    <input type="submit" value="submit me!" />
</form>

IMAGE SUBMIT 変数名

フォームを投稿する際、次のタグのように標準の投稿ボタンの代わりに 画像を使用することができます。

<input type="image" src="image.gif" name="sub" />

画像のどこかがクリックされた場合、二つの変数 sub_x および sub_y が付け加えられてこのフォームはサーバーに転送されます。これらの変 数は、ユーザーがこの画像をクリックした座標を示しています。経験の ある人は、ブラウザにより送られた変数の名前においてアンダースコア がピリオドになってしまっていることを心配するかもしれません。 しかし、PHP はピリオドをアンダースコアに自動的に変換します。

HTTP Cookie

PHP は、» RFC 6265 に定義されたHTTP Cookieを完全にサポートします。Cookieは、リモート ブラウザにデータを保持し、再訪するユーザーを追跡し、特定する機構 です。setcookie() 関数によりCookieをセットす ることができます。Cookieは、HTTP ヘッダの一部なので、SetCookie 関数をブラウザに何かを出力する前にコールする必要があります。 この制約は、header() 関数のものと同じです。 Cookieのデータは、$_COOKIE のような適当なCookieデータ 配列で参照可能です。また、 $_REQUESTでも 参照可能です。詳細および例については、 setcookie()のマニュアルページを参照してください。

単一のCookieに複数の値を代入したい場合は、配列として 代入することが可能です。以下に例を示します。

<?php
  setcookie
("MyCookie[foo]"'Testing 1'time()+3600);
  
setcookie("MyCookie[bar]"'Testing 2'time()+3600);
?>

上記スクリプトにおいては、2つの異なるCookieを生成されますが、 この場合、スクリプトでは MyCookie という単一の配列になります。 一つのCookieに複数の値を設定したい場合、最初の値に serialize()または explode()を用いることを考えてください。

Cookieは、パスまたはドメインが異ならない限り、 以前のクッキーをブラウザ上の同じ名前の変数に置き換えることに 注意してください。 さて、買い物かご(Shopping Cart) プログラムの場合、カウンタを保持し、 受け渡したいと思うかもしれません。 これは、次のようになります。

例5 setcookie()の例

<?php
if (isset($_COOKIE['count'])) {
    
$count $_COOKIE['count'] + 1;
} else {
    
$count 1;
}
setcookie('count'$counttime()+3600);
setcookie("Cart[$count]"$itemtime()+3600);
?>

外部変数名のドット

通常、PHP はスクリプトに渡された変数の名前を変更しません。しかし、 ドット(ピリオド、終止符)はPHPの変数名で有効な文字ではないというこ とに注意する必要があります。次の例を見てみましょう。

<?php
$varname
.ext;  /* 無効な変数名 */
?>
ここで、パーサは、$varnameという名前の変数の後に 文字列結合演算子があり、その後に、裸の文字列(すなわち、既知のキー または予約語にマッチしない引用符無しの文字列) 'ext' が続くとして 解釈します。この場合、明らかに意図する結果にはなりません。

重要なことを記述しておくと、このため、外部変数に含まれるドットを PHP は自動的にアンダースコアに変換します。

変数の型の定義

PHPは、変数の型を定義し、必要に応じて変換します。このため、ある変 数の型がある時点で常に明らかであるわけではありません。PHPは、変数 の型を調べる複数の関数をサポートしています。それらは、 gettype(), is_array(), is_float(), is_int(), is_object(), is_string() です。 の章も参照ください。

変更履歴

バージョン 説明
5.4.0 グローバル変数の登録機能マジッククォートおよび register_long_arrays が削除されました。
5.3.0 グローバル変数の登録機能マジッククォートおよび register_long_arrays が非推奨となりました。
4.2.0 register_globals のデフォルトが off になりました。
4.1.0 スーパーグローバル配列、 つまり $_POST$_GET が使えるようになりました。

add a note add a note

User Contributed Notes 34 notes

up
5
Anonymous
7 months ago
From HTML 5.1 Draft:
http://www.w3.org/html/wg/drafts/html/master/forms.html#naming-form-controls:-the-name-attribute

The name content attribute gives the name of the form control, as used in form submission and in the form element's elements object. If the attribute is specified, its value must not be the empty string.
Any non-empty value for name is allowed.

So use the format like this <select multiple name="beer[]"> is still in the HTML 5 standard.
up
5
lennynyktyk at yahoo dot com
10 years ago
When dealing with multiple select boxes and the name=some_name[] so that PHP will understand that is needs to interpet the input as an array an not as a single value. If you want to access this in Javascript you should assign an id attribute to the select box as well as the name attribute. Then proceed to use the id attribute in Javascript to reference the select box and the name attribute to reference the select box in PHP.
Example

<select multiple id="select_id" name="select_name[]">
....

</select>

<?PHP
   
echo $select_name[0];
?>

<script language="javascript">
  document.forms[0].select_id.options[0].selected = true;
</script>

I hope you get the idea
up
4
Anonymous
6 years ago
The full list of field-name characters that PHP converts to _ (underscore) is the following (not just dot):
chr(32) ( ) (space)
chr(46) (.) (dot)
chr(91) ([) (open square bracket)
chr(128) - chr(159) (various)

PHP irreversibly modifies field names containing these characters in an attempt to maintain compatibility with the deprecated register_globals feature.
up
2
Murat TASARSU
9 years ago
if you want your multiple select returned variable in comma seperated form you can use this. hope that helps. regards...

$myvariable
   Array ( [0] => one [1] => two [2] => three )
turns into
   one,two,three

<?php
$myvariable
="";
$myseperator="";
foreach (
$_POST["myvariable"] as $v) {
if (!isset(
$nofirstcomma)) $nofirstcomma=0; else $myseperator=",";
$myvariable = $myvariable.$myseperator.$v;
}
echo
$myvariable;
?>
up
2
un shift at yahoo dot com
11 years ago
This function takes a recurring form item from php://input and loads it into an array - useful for javascript/dom incompatibility with form_input_item[] names for checkboxes, multiple selects, etc.  The fread maxes out at 100k on this one.  I guess a more portable option would be pulling in ini_get('post_max_size') and converting it to an integer.

<?php
function multi_post_item($input_item_name) {
    
$array_output = array();
    
$in_handle = fopen("php://input", "r");
    
$raw_input_items = split("&", urldecode(fread($in_handle, 100000)));
     foreach (
$raw_input_items as $input_item) {
           
// split this item into name/value pair
           
$item = split("=", $input_item);
           
// form item name
           
$item_name = $item[0];
           
// form item value
           
$item_value = $item[1];
            if (
$item_name == $input_item_name) {
                   
$array_output[] = $item_value;
            }
     }
     return
$array_output;
}
?>
up
3
vierubino dot r3m0oFdisB1T at gmail dot com
7 years ago
When you are using checkboxes to submit multiple choices, there is no need to use the complex method further down the page where you assign a unique name to each checkbox.

Instead, just name each checkbox as the same array, e.g.:

<input type="checkbox" name="items[]" value="foo" />
<input type="checkbox" name="items[]" value="bar" />
<input type="checkbox" name="items[]" value="baz" />

This way your $_POST["items"] variable will return as an array containing all and only the checkboxes that were clicked on.
up
2
walf
3 years ago
WARNING! replacement of spaces and dots does not occur in array keys.

E.g. If you have
<input name="a. b[x. y]" value="foo" />

var_dump($_POST);
gives
array(1) {
  ["a__b"]=>
  array(1) {
    ["x. y"]=>
    string(3) "foo"
  }
}
up
1
tim at timpauly dot com
9 years ago
This code module can be added to every form using require_once().
It will process any and all form data, prepending each variable with
a unique identifier (so you know which method was used to get the data).

My coding could be neater, but this sure makes processing forms much easier!

<?php
// -----------------------------------------------------------------
// Basic Data PHP module. This module captures all GET, POST
// and COOKIE data and processes it into variables.
// Coded April, 2005 by Timothy J. Pauly
// -----------------------------------------------------------------
//
// coo_ is prepended to each cookie variable
// get_ is prepended to each GET variable
// pos_ is prepended to each POST variable
// ses_ is prepended to each SESSION variable
// ser_ is prepended to each SERVER variable

session_start(); // initialize session data
$ArrayList = array("_POST", "_GET", "_SESSION", "_COOKIE", "_SERVER"); // create an array of the autoglobal arrays
// we want to process

foreach($ArrayList as $gblArray) // process each array in the array list
{
  
$prefx = strtolower(substr($gblArray,1,3))."_"; // derive the prepend string
// from the autoglobal type name
  
$tmpArray = $$gblArray;
  
$keys = array_keys($tmpArray); // extract the keys from the array being processed
  
foreach($keys as $key) // process each key
   
{
      
   
$arcnt = count($tmpArray[$key]);
   
    if (
$arcnt > 1) // Break down passed arrays and
// process each element seperately
   
{
     
$lcount = 0;
      foreach (
$tmpArray[$key] as $dval)
        {
          
$prkey = $prefx.$key; // create a new key string
// with the prepend string added
          
$prdata['$prkey'] = $dval; // this step could be eliminated
          
${$prkey}[$lcount] = $prdata['$prkey']; //create new key and insert the data
          
$lcount++;
        }
     
        } else {
// process passed single variables
       
               
$prkey = $prefx.$key; // create a new key string
// with the prepend string added
               
$prdata['$prkey'] = $tmpArray[$key]; // insert the data from
// the old array into the new one
               
$$prkey = $prdata['$prkey']; // create the newly named
// (prepended) key pair using variable variables :-)
              
               
              
}
    }
}

// -------------------------------------------------------------
?>
up
1
mattij at nitro fi no at no dot no
9 years ago
If you try to refer or pass HTML-form data which has arrays with javascript remember that you should point to that array like this

<script type="text/javascript">
    window.opener.document.forms[0]["to[where][we][point]"];
</script>
up
1
kevinrlat nospam dot ccs dot neu dot edu
11 years ago
if you use an array of checkboxes to submit info to a database or what have you, be careful of the case when no boxes are checked.  for example:

<form method="post">
<input type="checkbox" name="checkstuff[]" value="0">
<input type="checkbox" name="checkstuff[]" value="1">
<input type="checkbox" name="checkstuff[]" value="2">

. . .

</form>

if these are submitted and none are checked, the $_POST['checkstuff'] variable will not contain an empty array, but a NULL value.  this bothered me when trying to implode() the values of my checkboxes to insert into a database, i got a warning saying the 2nd argument was the wrong type. 

hope this helps!
-kevin
up
0
johnbendie at gmail dot com
7 months ago
Please describe how the request is built and passed to the script on the server side. That will make things more clearer. Or provide a link detailing such process. Don't assume anything.
up
0
user: "someuser" at mai1server "ua.fm"
9 years ago
Numerous string like:

<?php
if (isset($_POST["var1"]))
   
$var1=$_POST["var1"];
else
$var1='';
//...
if (isset($_POST["varN"]))
   
$varN=$_POST["varN"];
else
$varN='';
?>

Can be replaced with:

<?php
get_superglobal_vars_from_POST
('var1','...','varN');

function
get_superglobal_vars_from_POST()
{
   
$numargs = func_num_args();
   
$setargs = 0; // for counting set variables
   
for ($i=0; $i<$numargs; $i++)
    {
   
$varname=func_get_arg($i);
    if (!isset(
$_POST[$varname]))
       
$result='';
    else
    {
       
$result=$_POST[$varname];
       
$setargs++;
    }   
   
$GLOBALS["$varname"]=$result;
    }
    return
$setargs; // who cares?
}
?>
up
0
tmk-php at infeline dot org
9 years ago
To handle forms with or without [] you can do something like this:

<?php
   
function repairPost($data) {
       
// combine rawpost and $_POST ($data) to rebuild broken arrays in $_POST
       
$rawpost = "&".file_get_contents("php://input");
        while(list(
$key,$value)= each($data)) {
           
$pos = preg_match_all("/&".$key."=([^&]*)/i",$rawpost, $regs, PREG_PATTERN_ORDER);       
            if((!
is_array($value)) && ($pos > 1)) {
               
$qform[$key] = array();
                for(
$i = 0; $i < $pos; $i++) {
                   
$qform[$key][$i] = urldecode($regs[1][$i]);
                }
            } else {
               
$qform[$key] = $value;
            }
        }
        return
$qform;
    }

   
// --- MAIN

   
$_POST = repairPost($_POST);
?>

The function will check every field in the $_POST with the raw post data and rebuild the arrays that got lost.
up
0
jlratwil at yahoo dot com
9 years ago
To get multiple selected (with "multiple" ) lists in <select> tag, make sure that the "name" attribute is added to braces, like this:

<select multiple="multiple" name="users[]">
     <option value="foo">Foo</option>
     <option value="bar">Bar</option>
</select>

When submitted to PHP file (assume that you have a complete form) it will return an array of strings. Otherwise, it will just return the last element of the <select> tag you selected.
up
0
arjini at mac dot com
10 years ago
When dealing with form inputs named_like_this[5] and javascript, instead of trying to get PHP to do something fancy as mentioned below, just try this on the javascript side of things:

<form name="myForm">

<script>
my_fancy_input_name = 'array_of_things[1]';
/* now just refer to it like this in the dom tree

document[myForm][my_fancy_input_name].value

etc*/
</script>

<input type="text" name="array_of_things[1]" value="1"/>
</form>

No fancy PHP, in fact, you shouldn't need to change your PHP at all.
up
0
jim at jamesdavis dot it
10 years ago
How to pass a numerically indexed array.
This is the part inside the form. Notice that the name is not 'english[$r]' which you would normally write, but 'english[]'. PHP adds the index when it receives the post and it starts at 0.

<?php

for ($r=0; $r <= count($english)-1; $r++){
         echo
"<TEXTAREA NAME='english[]'>".$english[$r]."</TEXTAREA>";       
         
}
?>
<?php

And this will get it out at the other end
function retrieve_english(){
    for (
$r=0; $r <= count($_POST['english'])-1; $r++){
        echo
$_POST['english'][$r]."<BR>";
    }
}
?>

Keys are useful but so are numerical indices!
Cheers everyone
up
0
darren at sullivan dot net
10 years ago
This function is a simple solution for getting the array of selectes from a checkbox list or a dropdown list out of the Querry String. I took an example posted earlier and simplified it.

<?php
function multi_post_item($repeatedString) {
   
// Gets the specified array of multiple selects and/or
    // checkboxes from the Query String
   
$ArrayOfItems = array();
   
$raw_input_items = split("&", $_SERVER["QUERY_STRING"]);
    foreach (
$raw_input_items as $input_item) {
       
$itemPair = split("=", $input_item);
        if (
$itemPair[0] == $repeatedString) {
           
$ArrayOfItems[] = $itemPair[1];
        }
    }
    return
$ArrayOfItems;
}
?>

Use the name of the field as the agrument. Example:

<?php
$Order
= $_GET['Order'];
$Name = $_GET['Name'];
$States = multi_post_item('States');
$Products = multi_post_item('Products');
?>

Be sure to check for NULL if there are no selections or boxes checked.
up
0
soeren at hattel dot dk
10 years ago
The decision in PHP to translate a query string like:

a=2&a=3&a=4

into one single variable a=4 is simply strupid!

The "wonderful" hack allowing multiple values to be read only if one uses:

a[]=2&a[]=3&a[]=4

is - at first sight - a nice feature but soon become a pain in the a..!

In ASP and ASPX the first situation is handled as:

a=2,3,4

which is better than the PHP behaviour but still bad (what if your variable values contain commas?).

It seems to me that the proper behaviour would be:

a=2&a=3&a=4

automatically generates an array with all the variables inside. I know this would require proper error handling but evevy things does anyway!
up
0
vb at bertola dot eu dot org
11 years ago
For what I understand, since PHP 4.3 it is possible to access the content of a POST request (or other methods as well) as an input stream named php://input, example:

readfile("php://input");  
[to display it]

or

$fp = fopen("php://input", "r");   
[to open it and then do whatever you want]

This is very useful to access the content of POST requests which actually have a content (and not just variable-value couples, which appear in $_POST).

This substitutes the old $HTTP_RAW_POST_DATA variable available in some of the previous 4.x versions. It is available for other upload methods different from POST too, but it is not available for POSTs with multipart/form-data content type, since the file upload handler has already taken care of the content in that case.
up
0
Anonymous
11 years ago
"...the dot (period, full stop) is not a valid character in a PHP variable name."

That's not completely correct, consider this example:
$GLOBALS['foo.bar'] = 'baz';
echo ${'foo.bar'};
This will output baz as expected.
up
0
keli at kmdsz dot ro
11 years ago
image type inputs apparently return their "value" argument from Mozilla, but not from IEXplorer... :(

example:

<input type="image" name="sb" value="first" src="first.jpg">

using a mozilla will give you
  $sb="first" AND $sb_x, $sb_y ... whereas from IE there's just no $sb. :(

[this in short form, as I'm still using trackvars :) ]
up
0
a at b dot c dot de
12 years ago
As far as whether or not "[]" in name attributes goes, The HTML4.01 specification only requires that it be a case-insensitive CDATA token, which can quite happily include "[]". Leading and trailing whitespace may be trimmed and shouldn't be used.

It is the id= attribute which is restricted, to a case-sensitive NAME token (not to be confused with a name= attribute).
up
0
yasuo_ohgaki at hotmail dot com
13 years ago
Important:  Pay attention to the following security concerns when handling user submitted  data :

http://www.php.net/manual/en/security.registerglobals.php
http://www.php.net/manual/en/security.variables.php
up
-1
POSTer
4 years ago
Here's a simple function to give you an uncorrupted version of $_POST:

<?php
// Function to fix up PHP's messing up POST input containing dots, etc.
function getRealPOST() {
   
$pairs = explode("&", file_get_contents("php://input"));
   
$vars = array();
    foreach (
$pairs as $pair) {
       
$nv = explode("=", $pair);
       
$name = urldecode($nv[0]);
       
$value = urldecode($nv[1]);
       
$vars[$name] = $value;
    }
    return
$vars;
}
?>
up
-1
ch1902uk at hotmail dot com
8 years ago
Regarding image input buttons, above where it says:

"When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two *additional* variables, sub_x and sub_y. These contain the coordinates of the user click within the image."

This is the case with Firefox (and probably other standards browsers), however my experience with Internet Explorer is that when image inputs are clicked, they only submit the location of the click on the button and *not* the name of the input.

So if you have a form to move/delete entries like this

entry[]  [delete_0] [up_0] [down_0]
entry[]   [delete_1] [up_1] [down_1]
entry[]   [delete_2] [up_2] [down_2]

Then submitting the form in firefox will give you post variables such as

<?php
   $_POST
['delete_2'];   // "Delete" - button value
  
$_POST['delete_2_x'];   // 23 - x coord
  
$_POST['delete_2_y'];   // 3 - y coord
?>

In IE you only get

<?php
   $_POST
['delete_2_x'];   // 23 - x coord
  
$_POST['delete_2_y'];   // 3 - y coord
?>

So if you are checking for what button was clicked do something like this

<?php
  
for ($i = 0; $i < count($_POST['entry']); $i++)
   {
      if (isset(
$_POST['delete_' . $i . '_x']))
      {
        
// do delete
     
}
   }
?>
up
-1
krydprz at iit dot edu
9 years ago
This post is with regards to handling forms that have more than one submit button.

Suppose we have an HTML form with a submit button specified like this:

<input type="submit" value="Delete" name="action_button">

Normally the 'value' attribute of the HTML 'input' tag (in this case "Delete") that creates the submit button can be accessed in PHP after post like this:

<?php
$_POST
['action_button'];
?>

We of course use the 'name' of the button as an index into the $_POST array.

This works fine, except when we want to pass more information with the click of this particular button.

Imagine a scenario where you're dealing with user management in some administrative interface.  You are presented with a list of user names queried from a database and wish to add a "Delete" and "Modify" button next to each of the names in the list.  Naturally the 'value' of our buttons in the HTML form that we want to display will be "Delete" and "Modify" since that's what we want to appear on the buttons' faceplates.

Both buttons (Modify and Delete) will be named "action_button" since that's what we want to index the $_POST array with.  In other words, the 'name' of the buttons along cannot carry any uniquely identifying information if we want to process them systematically after submit. Since these buttons will exist for every user in the list, we need some further way to distinguish them, so that we know for which user one of the buttons has been pressed.

Using arrays is the way to go.  Assuming that we know the unique numerical identifier of each user, such as their primary key from the database, and we DON'T wish to protect that number from the public, we can make the 'action_button' into an array and use the user's unique numerical identifier as a key in this array.

Our HTML code to display the buttons will become:

<input type="submit" value="Delete" name="action_button[0000000002]">
<input type="submit" value="Modify" name="action_button[0000000002]">

The 0000000002 is of course the unique numerical identifier for this particular user.

Then when we handle this form in PHP we need to do the following to extract both the 'value' of the button ("Delete" or "Modify") and the unique numerical identifier of the user we wish to affect (0000000002 in this case). The following will print either "Modify" or "Delete", as well as the unique number of the user:

<?php
$submitted_array
= array_keys($_POST['action_button']);
echo (
$_POST['action_button'][$submitted_array[0]] . " " . $submitted_array[0]);
?>

$submitted_array[0] carries the 0000000002.
When we index that into the $_POST['action_button'], like we did above, we will extract the string that was used as 'value' in the HTML code 'input' tag that created this button.

If we wish to protect the unique numerical identifier, we must use some other uniquely identifying attribute of each user. Possibly that attribute should be encrypted when output into the form for greater security.

Enjoy!
up
-1
steiner277 at charter dot net
12 years ago
When accessing variables from a post, do NOT put $_POST['fieldname'] in double quotes or you will get an error message.

e.g. the following works fine:

$msg = "The message is:\t" . $_POST['message'] . "\n";

but the following will cause errors:

$msg = "The message is:\t$_POST['message']\n";
up
-1
hjncom at hjncom dot net
12 years ago
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)
up
-1
jesper at codecrew dot dk
12 years ago
Just to help others with the same stupid problem i have:

I you use a checkbox in your form, it will only return the value specified in value if it is checked.

ex. <input type="checkbox" value="yes">

in php code you then write

$checkboxchecked = ($checkbox == "yes");

I guess :)
up
-1
carl_steinhilber at NOSPAMmentor dot com
12 years ago
A group of identically-named checkbox form elements returning an array is a pretty standard feature of HTML forms. It would seem that, if the only way to get it to work is a non-HTML-standard-compliant workaround, it's a problem with PHP.

Since the array is passed in the header in a post, or the URL in a get, it's the PHP interpretation of those values that's failing.
up
-2
t.montg AT gmail DOT com
7 years ago
For anyone else having trouble figuring out how to access values in a SELECT element from a POST or GET form, you can't set the "id" attribute to the same thing as your "name" attribute.  i.e. don't do this:

<?php
 
//Not so good
 
<select multiple="multiple" id="selectElem" name="selectElem[]">
     <
option value="ham">Ham</option>
     <
option value="cheese">Cheese</option>
     <
option value="hamcheese">Ham and Cheese</option>
  </
select>
?>

If you do the above, the variable $_POST['selectElem'] will not be set.  Instead, either change the id or name attribute so that they are dissimilar.  i.e. do this:

<?php
 
//So good (notice the new "id" value)
 
<select multiple="multiple" id="selectElemId" name="selectElem[]">
     <
option value="ham">Ham</option>
     <
option value="cheese">Cheese</option>
     <
option value="hamcheese">Ham and Cheese</option>
  </
select>
?>

Then you can access the value(s) of the SELECT element through the array $_POST['selectElem'][] or $_GET['selectElem'][].  It took me quite some time to figure out the problem.
up
-2
__kbanks at (__ignoreunderscores) dot gmail dot com
9 years ago
Hi all:

I'm presently building a solution to programmatically build, view, and validate HTML forms when I came across the ol' PHP non-scalar form variable handling problem.  Because my form validator class would really have no way of knowing if a given form variable was meant to be scalar or not, I decided to TREAT ALL PHP FORM VARIABLES AS ARRAYS, i.e., to use the '[]' syntax for all variables, scalar or not.  This way, the form designer need not remember to specify the '[]' syntax, and the Form->HTML transformer need not scan for every input within the form, looking for duplicate names.  This also eliminates the risk of losing data you meant to keep in an array but to which you forgot to apply the '[]' syntax. 

You may then either treat all form variables as arrays in your form handling code, or you may, as I intend to do, filter each HTML request through a Front Controller (desc. in Fowler, PoEAA).  The Front Controller would convert all arrays of length 1 to a scalar variable and leave multi-element arrays as they are.  This should essentially convert PHP's handling of non-scalar form variables to that of ASP's (or slightly better, since multiple form values of the same name will actually be arrays, not just comma-seperated values). 

This way my Form Validator class can just check if the input to validate is an array, and then apply some constraint across each element in the array.
up
-2
mail at paulodeon dot com
11 years ago
If you have form data that could be coming in via either GET or POST and register_globals is off (as it should be) use the empty() function to find out where the data is coming from, as in the following example

<?php
if(empty($_GET)) {
       
$clientfilter = $_POST['clientfilter'];
       
$branchfilter = $_POST['branchfilter'];
}
if(empty(
$_POST)) {
   
$clientfilter = $_GET['clientfilter'];
   
$branchfilter = $_GET['branchfilter'];
}
?>
up
-3
aescomputer AT yahoo DOT com
8 years ago
Here are two usefull functions for forms:

<?php
// clean html tags out of url attributes
   
if(!empty($_REQUEST)){
        foreach(
$_REQUEST as $x => $y){
           
$_REQUEST[$x] = str_replace('<', '&lt;', str_replace('>', '&gt;', $y));
        }
    }

// replace carrage returns in url attributes with <br>
   
if(!empty($_REQUEST)){
        foreach(
$_REQUEST as $x => $y){
           
$_REQUEST[$x] = str_replace("\n", '<br>', $y);
        }
    }
?>
To Top