PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

PHP et COM> <Utiliser PHP
Last updated: Fri, 05 Sep 2008

view this page in

PHP et HTML

PHP et HTML sont très interactifs : PHP peut générer du HTML et HTML peut passer des informations à PHP. Avant de lire cette faq (foire aux questions), il est important que vous appreniez comment récupérer des variables externes à PHP. La page du manuel correspondante contient beaucoup d'exemples. Faites particulièrement attention à ce que signifie register_globals.

    Quel encodage/décodage ai-je besoin lors du passage d'une valeur via un formulaire/une URL ?

    Il y a plusieurs étapes pour lesquelles le codage est important. En supposant que vous avez une chaîne de caractères $data, qui contient la chaîne que vous voulez passer de manière non-encodée, voici les étapes appropriées :

    • Interprétation HTML. Afin d'indiquer une chaîne aléatoire, vous devez l'inclure entre doubles guillemets et utiliser la fonction htmlspecialchars() pour encoder la chaîne.

    • URL : une URL est constituée de plusieurs parties. Si vous voulez que vos données soient interprétées comme un seul élément, vous devez les encoder avec la fonction urlencode().

    Exemple #1 Un élément de formulaire HTML caché

    <?php
    echo '<input type="hidden" value="' htmlspecialchars($data) . '" />';
    ?>

    Note: Il n'est pas correct d'utiliser la fonction urlencode() pour vos données $data, car il en est de la responsabilité du navigateur de les encoder. Tous les navigateurs populaires le font correctement. Notez que cela s'effectue sans considération de la méthode utilisée (c'est-à-dire GET ou POST). Vous devez uniquement noter ce cas pour les requêtes GET, car les requêtes POST sont généralement cachées.

    Exemple #2 Données éditables par l'utilisateur

    <?php
    echo "<textarea name=\"mydata\">\n";
    echo 
    htmlspecialchars($data)."\n";
    echo 
    '</textarea>';
    ?>

    Note: Les données sont montrées dans le navigateur comme prévues, car celui-ci interprétera les symboles HTML échappés. Au moment de la validation, via la méthode GET ou POST, les données devraient être url-encodées par le navigateur avant le transfert et directement url-décodées par PHP. Donc, finalement, vous n'avez pas à effectuer d'url-encodage/url-decodage vous-même, tout est effectué automatiquement.

    Exemple #3 Dans une URL

    <?php
    echo "<a href=\"" htmlspecialchars("/nextpage.php?stage=23&data=" .
            
    urlencode($data)) . "\">\n";
    ?>

    Note: En fait, vous simulez une requête GET HTML, il est nécessaire d'utiliser manuellement la fonction urlencode() sur vos données.

    Note: Vous devez utiliser htmlspecialchars() sur l'URL complète, car l'URL se comporte comme la valeur d'un attribut HTML. Dans ce cas, le navigateur fera un htmlspecialchars() sur la valeur et passera le résultat à l'URL. PHP devrait comprendre l'URL correctement, car vous avez url-encodé les données. Vous devez noter que & dans l'URL est remplacé par &amp;. Bien que la plus part des navigateurs devraient corriger cela si vous l'oubliez, ce n'est pas toujours le cas. Donc, même si votre URL n'est pas dynamique, vous devez utiliser la fonction htmlspecialchars() sur l'URL.

    J'essaye d'utiliser <input type="image"> mais les variables $foo.x et $foo.y ne sont pas disponibles. $_GET['foo.x'] n'existe pas non plus. Où sont-elles ?

    Lorsque vous validez un formulaire, il est possible d'utiliser une image au lieu du bouton standard de type "submit" avec une balise du type :

    <input type="image" src="image.gif" name="foo" />
    
    Lorsque l'utilisateur clique sur l'image, le formulaire est transmis au serveur avec deux variables supplémentaires : foo.x et foo.y qui représentent les coordonnées du point cliqué.

    Comme foo.x et foo.y sont des noms de variables invalides en PHP, elles sont automatiquement converties en foo_x et foo_y. Les points sont remplacés par des soulignés. Donc, vous devez accéder à ces variables comme n'importe quelle autre variable tel que décrit dans la section "Variables provenant d'autres sources". Par exemple, en utilisant $_GET['foo_x'].

    Note: Les espaces dans les noms de variables sont également converties en un souligné bas.

    Comment créer un tableau dans une balise <form> HTML ?

    Pour envoyer le résultat du <form> comme un tableau de variables à votre script PHP, vous devez nommer, via l'attribut name, les balises <input>, <select> ou <textarea> comme cela :

    <input name="MonTableau[]" />
    <input name="MonTableau[]" />
    <input name="MonTableau[]" />
    <input name="MonTableau[]" />
    
    Noter les crochets après le nom de la variable, c'est ce qui fait que celle-ci sera un tableau. Vous pouvez grouper les éléments dans différents tableaux de variables en assignant le même nom à différents éléments :
    <input name="MonTableau[]" />
    <input name="MonTableau[]" />
    <input name="MonAutreTableau[]" />
    <input name="MonAutreTableau[]" />
    
    Cela produira deux tableaux de variables, MonTableau et MonAutreTableau, qui seront envoyés au script PHP. Il est également possible d'assigner des clés spécifiques à votre tableau :
    <input name="UnAutreTableau[]" />
    <input name="UnAutreTableau[]" />
    <input name="UnAutreTableau[email]" />
    <input name="UnAutreTableau[telephone]" />
    
    Le tableau UnAutreTableau contiendra les clés 0, 1, email et telephone.

    Note: Le fait de spécifier une clé à un tableau est optionnel en HTML. Si vous ne le faites pas, les clés du tableau suiveront l'ordre d'apparition des éléments dans le formulaire. Dans notre premier exemple, le tableau contient les clés 0, 1, 2 et 3.

    Voir aussi les fonctions sur les tableaux de variables et la section sur les variables provenant d'autres sources.

    Comment puis-je récupérer le résultat d'un champ HTML SELECT multiple ?

    Le champ SELECT multiple en HTML permet à l'utilisateur de sélectionner plusieurs éléments d'une liste. Ces éléments seront transmis à la page pointée par l'attribut action de la balise form. Le problème est que ces éléments sont tous passés avec le même nom de variable.

    <select name="var" multiple="yes">
    
    Chaque option sélectionnée arrivera au mécanisme de traitement sous la forme :
    var=option1
    var=option2
    var=option3
          
    Chaque option effacera donc le contenu de la précédente variable $var. La solution consiste à utiliser un tableau de variables dans cet élément de formulaire HTML, par exemple :
    <select name="var[]" multiple="yes">
    
    Cela fera que PHP traitera $var comme un tableau de variables et que chaque assignement de valeur à var[] ajoutera un index au tableau. La première option choisie sera mise dans $var[0], la suivante sera mise dans $var[1], etc. La fonction count() peut être utilisée pour déterminer combien d'options ont été sélectionnées, et la fonction sort() peut être utilisée pour trier le tableau, si nécessaire.

    Notez que si vous utilisez Javascript, [] dans le nom de l'élément peut vous poser problème lorsque vous tenterez d'accéder à celui-ci par son nom. Utilisez plutôt l'indice numérique de l'élément dans ce cas, ou bien utilisez les simples guillemets pour entourer cet élément, comme :

    variable = documents.forms[0].elements['var[]'];
          

    Comment puis-je passer une variable de Javascript vers PHP ?

    Javascript est (habituellement) une technologie côté client et PHP est (habituellement) une technologie côté serveur et sachant que HTTP est un protocole statique, les deux langages ne peuvent pas directement partager des variables.

    Cependant, il est possible de faire passer des variables entre les deux. Une des solutions pour cela est de générer un code Javascript à l'aide de PHP et de faire rafraîchir le navigateur tout seul, passant ainsi des variables spécifiques au script PHP. L'exemple suivant montre précisément comme réaliser cela -- il permet à PHP de récupérer les dimensions de l'écran du client, ce qui est normalement possible qu'en technologie coté client.

    <?php
    if (isset($_GET['largeur']) AND isset($_GET['hauteur'])) {
      
    // Affichage des variables
      
    echo 'La largeur de l\'écran est : ' $_GET['largeur'] ."<br />\n";
      echo 
    'La hauteur de l\'écran est : ' $_GET['hauteur'] . "<br />\n";
    } else {
      
    // passage des variables de dimensions
      // (préservation de la requête d'origine
      //   -- les variables par méthode POST doivent être traitées différemment)

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



    PHP et COM> <Utiliser PHP
    Last updated: Fri, 05 Sep 2008
     
    add a note add a note User Contributed Notes
    PHP et HTML
    Andreas R.
    01-May-2007 02:14
    Actually Example 56.1 doesn't conform to what is stated in the text above it, namely:
    * HTML interpretation. In order to specify a random string, you must include it in double quotes, and htmlspecialchars() the whole value.
    In the example code single quotes are used instead of double quotes:
    <?php
        
    echo "<input type='hidden' value='" . htmlspecialchars($data) . "' />\n";
     
    ?>
    which should be instead:
    <?php
        
    echo "<input type='hidden' value=\"" . htmlspecialchars($data) . "\" />\n";
     
    ?>
    If single quotes are used, they should be escaped too using ENT_QUOTES quote style for htmlspecialchars.
    francesco
    07-Nov-2006 03:41
    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
    12-Aug-2006 01:34
    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...
    dot dot dot NO php SPAM at NO willfris dot nl SPAM dot dot dot
    12-Jul-2006 12:19
    @Torsten{
    In http://www.w3.org/TR/xhtml1/#C_8 it says:
    "Unfortunately, this constraint cannot be expressed in the XHTML 1.0 DTDs."
    }

    http://www.w3.org/TR/xhtml1/#C_8 also says: "When defining fragment identifiers to be backward-compatible, only strings matching the pattern [A-Za-z][A-Za-z0-9:_.-]* should be used."
    I'll come back to this.

    Since it's all about fragment identifiers, I can't see why using an array like arrayname[] would be used. I think arrayname[name] should be used this way the fragment identifiers stay unique.
    Since [ and ] are not allowed, why not use something what is allowed and use str_replace?
    example:   :_. = [ & ._: = ]   so: name="arrayname:_.name._:" OR name="arrayname:_.0._:" and offcourse also add the id attribute then for backward compatibility.
    Torsten
    22-Feb-2006 11:30
    Section C.8 of the XHTML spec's compatability guidelines apply to the use of the name attribute as a fragment identifier.  If you check the DTD you'll find that the 'name' attribute is still defined as CDATA for form elements.
    jetboy
    30-Dec-2005 04:06
    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.
    FatalError
    29-Dec-2005 11:29
    Actually, you can pass variables between JavaScript and PHP without even refreshing the page. To do this, you have to use AJAX, which is what dmsuperman at comcast dot net was showing in that example.
    tms at infamous dot net
    23-Nov-2005 03:23
    Regarding drane's claim that square brackets ([]) in form input elements (as PHP uses for arrays in forms) are invalid HTML: the NAME attribute of an input element is CDATA, not NAME or ID.

    Square brackets are allowed in CDATA, no problem.

    (Link is mangled because it's too long:

    http://www.w3.org/TR/1999/REC-html401-19991224/ interact/forms.html#h-17.4
    rybasso
    06-Oct-2005 11:19
    If U wish to build POST request depend on form which contains select-multiple use the following js code:

    var id = theForm.elements[e].id;

    if (theForm.elements[e].type=='select-multiple') {
                    for (f=0;f<theForm.elements[e].length;f++) {
                        if(theForm.elements[e].options[f].selected==true)
                             qs+= id+'['+f+']='+escape(theForm.elements[e].options[f].value);
                             qs+=(qs=='')?'':'&';   
                    }
                }
    dmsuperman at comcast dot net
    10-Sep-2005 06:05
    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>
    fuchs at michaelfuchs dot org
    09-Aug-2005 09:54
    Here's a new one, which might cause problems for people:

    To make my multiple select box contents accessible to both PHP and JavaScript (using getElementById()), I was using both name and id attributes - and naming them the same, for consistency:

    <select multiple="multiple" id="bob[]" name="bob[]">

    However, I've discovered that - for reasons unknown - using the brackets in the id causes only a single value (rather than multiple values) to get returned to the $_POST['bob'] array. What you want is:

    <select multiple="multiple" id="bob" name="bob[]">

    Hope this saves some time/frustration.
    fib at affordit dot fr
    13-Jul-2005 04:26
    I was working on a small interface for a client and he wanted a template to be generated dynamically. The issue came up when I had to retrieve the values for an array of text variables. I couldn't find any tutorial to help me out so after a few investigations this is how I made it work:
     
    <?php

      $line_class
    =array();
     
    $line_item=array();
     
        for (
    $i=$rows_number;$i>0;$i--)
          {
          
    $line_class[$i]=$_POST['line_class'.$i.''];
          
    $line_item[$i]=$_POST['line_item'.$i.''];
          }

    ?>

     Hope this helps someone ... at least they will do the job sooner than I did :D.
    levinb at cs dot rpi dot edu
    17-Jun-2005 06:17
    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];
                    }
            }
    }

    ?>
    noah at noah dot org
    10-May-2005 07:10
    In your action, "random_picker_action.php"
    shouldn't you initialize $picks? The code didn't work
    for me until I added the line:
        $picks = $_REQUEST['picks'];

    Here is the full random_picker_action.php

    Yours,
    Noah

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <html>
    <head>
       <title>How to Pass an Array from Javascript to PHP: Action Page</title>
      <!-- File: random_picker_action.php -->
    </head>
    <body>
    <p>
    <h3>How to Pass an Array from Javascript to PHP: Action Page</h3>
    <?php
      $picks
    = $_REQUEST['picks'];
     
    $picks = urldecode(stripslashes($picks));
      echo
    "<b>JavaScript said: " . $picks . "</b><p>";
     
    $picks = unserialize($picks);
      if(
    sizeof($picks) > 0)
      {
      
    reset($picks);
       echo
    "You picked the following items:<p>";
       while(
    $item = each($picks))
         echo 
    $item['value'] . " off, " . str_replace("_", " ", $item['key']) . "<br>";
      }
      else
       echo
    "You did not pick any items<p>";
    ?>
    </body>
    </html>
    richard dot prangnell at ntlworld dot com
    27-Feb-2005 06:09
    Further to my note posted on  26-Feb-2005 at 04:44, I have refined the JavaScript function "send_picks()" to make it more robust and universal. The original version was designed to handle string keys and +ve integer key values only; fine for the original purpose of handling random picks for a shopping cart application but it produced a mal-formed array if any -ve or non-integer key values were submitted. The new version treats both keys and key values as strings, irrespective of the data type; and we all know just how easy it is to manipulate numeric strings as numbers in PHP:-). Key values can now be anything you like; including:
    "5"
    "2 dozen"
    "A gross"
    "12.5"
    "blue"
    and so forth. Here's the updated code:

        <script type="text/javascript">
          function send_picks()
          {
            form1.picks.value="";
            var e, picked = 0;
            for (var i = 0 ; i < form1.elements.length - 2; i++)
            {
              e = form1.elements[i];
              if(e.value != "0" && e.value.length > 0)
              {
                e = form1.elements[i]
                picked++;
                    form1.picks.value = form1.picks.value + "s:"
                  + e.name.length + ":\"" + e.name + "\";s:"
                  + e.value.length + ":\"" + e.value + "\";";
              }
            }
            form1.picks.value = "a:" + picked + ":{" + form1.picks.value + "}";
          }
        </script>

    Note the line:
            for (var i = 0 ; i < form1.elements.length - 2; i++)
    The  "-2" term is to let the function skip the last 2 elements in the form, a "hidden" input and the "submit" button. No doubt different form layouts will need a different value here.
    An incidental bonus is that getting JavaScript to process a floating point input as a string rather than a number avoids the usual rounding errors that tend to turn an input such as "1.2" into a number beginning 1.199999... with about 30 places of decimals - yes, its JavaScript rather than PHP that is responsible for this kind of behaviour.
    richard dot prangnell at ntlworld dot com
    26-Feb-2005 05:44
    The following HTML form page and PHP action page illustrate an elegant and powerful client side JavaScript to server side PHP data transfer technique perfectly matched to PHP's associative array feature. Browse to the form page and select some items by entering an INTEGER > 1 then click on Submit (Don't put strings or reals in the input fields - error trapping has been stripped out for brevity). Try selecting one, some, all or none of the items, changing the names of the form input variables (and the associated labels, for clarity!) or adding to the number of items "on offer". At no point do you need to alter either the JavaScript function or the action page in any way - just be aware that extra coding and error trapping is required - especially where the key values in the application could be something other than integers:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <html>
    <head>
        <title>How to Pass an Array from Javascript to PHP: Form Page</title>
      <!-- File: random_picker.php -->
        <script type="text/javascript">
          function send_picks()
          {
            form1.picks.value="";
            var picked = 0;
            for (var i = 0 ; i < form1.elements.length; i++)
            {
              if(form1.elements[i].value > 0)
              {
                e = form1.elements[i]
                picked++;
                    form1.picks.value = form1.picks.value + "s:" + e.name.length + ":\""
                + e.name + "\";i:" + e.value + ";";

              }
            }
            form1.picks.value = "a:" + picked + ":{" + form1.picks.value + "}";
          }
        </script>
    </head>
    <body>
    <p>
    <h3 align="center">How to Pass an Array from Javascript to PHP: Form Page</h3>
    <form name="form1" action="random_picker_action.php" method="post"
      onsubmit="JavaScript:send_picks()">
    <table align="center" border="1" cellpadding="5" cellspacing="0">
      <tr><td>Item 13</td>
      <td><input type="text" name="item_13" value="0" size="4"></td>
      </tr>
      <tr><td>Part number 2</td>
      <td><input type="text" name="Part_number_2" value="0" size="4"></td>
      </tr>
      <tr><td>Drawing ref 327</td>
      <td><input type="text" name="Drawing_ref_327" value="0" size="4"></td>
      </tr>
      <tr><td>Organic Carrots</td>
      <td><input type="text" name="Organic_carrots" value="0" size="4"></td>
      </tr>
      <tr><td colspan="2" align="center">
          <input type="submit" value="Submit Picks">
          <input type="hidden" name="picks" value=""></td>
      </tr>
    </table>
    </form>
    </body>
    </html>

    The action page for the above form page is listed below. Notice the really ingenious feature; the form variable is simply unserialized  to turn it into a fully functional PHP array! The action page doesn't need to know anything about "expected" variable names because everything PHP needs to know is right inside the array. Note also that for maximum efficiency only "picked" item data is sent. If no items at all are picked, a perfectly formed empty array is sent:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <html>
    <head>
        <title>How to Pass an Array from Javascript to PHP: Action Page</title>
      <!-- File: random_picker_action.php -->
    </head>
    <body>
    <p>
    <h3>How to Pass an Array from Javascript to PHP: Action Page</h3>
    <?php
      $picks
    = urldecode(stripslashes($picks));
      echo
    "<b>JavaScript said: " . $picks . "</b><p>";
     
    $picks = unserialize($picks);
      if(
    sizeof($picks) > 0)
      {
       
    reset($picks);
        echo
    "You picked the following items:<p>";
        while(
    $item = each($picks))
          echo 
    $item['value'] . " off, " . str_replace("_", " ", $item['key']) . "<br>";
      }
      else
        echo
    "You did not pick any items<p>";
    ?>
    </body>
    </html>

    I hope you find this technique useful - let me know what you think - I can already hear the jaws of Java Jocks dropping!
    alberto dot delatorre at gmail dot com
    15-Jan-2005 08:41
    Other way to make a form with array fields, and use JavaScript features on them, is use both name and id attributes on the field as:

    <input type="text" name="myfield[]" id="myfield1"/>
    <input type="text" name="myfield[]" id="myfield2"/>
    <script language="JavaScript">
    document.getElementById("myfield1");
    document.getElementById("myfield2");
    </script>

    This is an easy way to do it. To number the fields, do a simple for structure and you have done.
    dreptack at op dot pl
    02-Jan-2005 09:37
    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
    seec77 at zahav dot net dot il
    22-Dec-2004 12:35
    Another unfortunate result of appending "[]" to input field names to pass form data in arrays to PHP, is that people will be able to detect you are running PHP. You can tell by the whole documentation section on hiding PHP, that some people might not want the public to know their site is generated with PHP (usually for security reasons), but the "[]" will blow your cover.
    So beware! If you are trying to hide PHP, you will have to stay away from passing form data as arrays!
    Karen
    05-Aug-2004 02:38
    I am using code I got from SitePoint that uses stripslashes because of magic quotes...I finally figured out that it kept my html form select multiple field from working correctly even though I was using name="arrName[]" as the field name -- I was only getting the word array as the value, and all the things I tried there was nothing else there. The stripslashes was part of an included include file, so it took me hours to debug.  Hopefully this will help keep others from wasting time.
    Jim Granger
    19-Jun-2004 07:11
    Kenn White wrote:

    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.

    I don't think they are going to deprecate name entirely. For one thing, to be of any use, radio boxes and occasionally checkboxes must have the same identifying mark, in this case a name. By the rules of the DTD, id's MUST be unique. In that respect, it is probably better to not use id in input elements at all.

    Of course, it's a good idea to use ids as sparingly as possible.
    ppmm at wuxinan dot net
    14-Jun-2004 01:11
    3. How do I create arrays in a HTML <form>?

    The feature is nice in the sense of simplifying programming. However, this does have side-effect. Look at this URL below:

    http://www.php.net/source.php?url[]=/index.php

    As a common viewpoint, exposing the absolute filesystem path in the webpage is always a bad thing. I reported this problem at bugs.php.net a few days before and I get a response saying "it's up to programmers". I think it's fair, however, webmaster should really learn to check the variables at the beginning of the script. In the above case, the PHP script should at least check like this:

    if (!is_string(url)) die("with some error message");

    As what I experienced, many PHP-based websites have this problem. I would think a perfect solution is that PHP does not do this automatic parsing, and when a PHP script expects an array to be posted, they would do something like

    parse_http_array($_GET, "url");

    only after this point, $_GET['url']) exists. Before this statement, only $_GET['url[]'] is available. Well, I am kind of too demanding I guess, but what I really intended to say is that webmaster should know this problem.
    vlad at vkelman dot com
    05-Jun-2004 04:04
    "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.
    Kenn White kennwhite dot nospam at hotmail dot com
    13-Mar-2004 05:18
    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
    davis at risingtiger dot net
    09-Jan-2004 09:14
    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>";
    }
    ?>
    email at njschedules dot com
    19-Oct-2003 06: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:

    <?php echo "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>"; ?>

    Hope I can save you from those nasty warning messages :)
    04-Oct-2003 12: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 08: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!
    martellare at hotmail dot com
    15-Mar-2003 09: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...

    <?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
    26-Nov-2002 08: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
    17-Nov-2002 09: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 06: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];
    hjncom at hjncom dot net
    25-May-2002 12: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)

    PHP et COM> <Utiliser PHP
    Last updated: Fri, 05 Sep 2008
     
     
    show source | credits | stats | sitemap | contact | advertising | mirror sites