PHP: PHP a HTML - Manual
PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<Pou��v�n� PHPPHP a COM>
view the version of this page
Last updated: Thu, 15 Jul 2004

Kapitola 53. PHP a HTML

PHP a HTML maj� hodn� spole�n�ho: PHP generuje HTML, a HTML m� informace, kter� budou posl�ny PHP.

1. Jak� zak�dov�n�/dek�dov�n� pot�ebuji, kdy� pos�l�m hodnotu p�es formul��? A v URL?
2. Zkou��m pou��t tag <input type="image">, ale prom�nn� $foo.x a $foo.y nejsou dostupn�. Kde jsou?
3. Jak vytvo��m pole ("array") v HTML formul��i?
4. Jak z�sk�m v�echna data z HTML elementu pro v�cen�sobn� v�b�r?

1. Jak� zak�dov�n�/dek�dov�n� pot�ebuji, kdy� pos�l�m hodnotu p�es formul��? A v URL?

Je v�ce situac�, pro kter� je zak�dov�n� d�le�it�. Za p�edpokladu, �e m�te string $data, kter� obsahuje �et�zec, jen� m�te nezak�dovan� a chcete ho poslat, je t�eba se zab�vat t�mito relevantn�mi probl�my:

  • HTML interpretace. Pokud specifikujete n�hodn� (obecn�) �et�zec, mus�te ho d�t do uvozovek a cel� ho zpracovat funkc� htmlspecialchars() (aby se odstranily/p�evedly speci�ln� znaky jazyka HTML).

  • URL: sest�v� z n�kolika ��st�. Pokud chcete, aby va�e data byla interpretov�na jako jedna polo�ka, mus�te je zak�dovat pomoc� urlencode().

P��klad 53-1. Skryt� element HTML formul��e

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

Pozn�mka: Je chybou pou��t urlencode() pro $data, proto�e prohl�e�e samy zaji��uj� zpracov�n� dat shodn� s funkc� urlencode(). V�echny obl�ben� prohl�e�e to d�laj� korektn�. Uv�domte si, �e toto nen� z�visl� na pou�it� metod� (nap�. GET nebo POST). V�imnete si toho v�ak pouze v p��pad� GET, proto�e po�adavky POST jsou obvykle skryt�.

P��klad 53-2. Data k editaci u�ivatelem

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

Pozn�mka: Data jsou v prohl�e�i zobrazena tak, jak bylo zam��leno, proto�e prohl�e� bude spr�vn� interpretovat speci�ln� symboly.

Po odesl�n�, a� ji� pomoc� GET nebo POST, data budou zak�dov�na zp�sobem urlencode pro p�enos a n�sledn� p��mo dek�dov�na v PHP. Tak�e v�bec nepot�ebujete prov�d�t ��dn� zak�dov�n�/dek�dov�n� ru�n�, v�e je prov�d�no automaticky.

P��klad 53-3. Uvnit� URL

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

Pozn�mka: V tomto p��pad� ji� opravdu vytv���te GET po�adavek, proto je nutn� data k�dovat ru�n� pomoc� urlencode().

Pozn�mka: Mus�te tak� pou��t htmlspecialchars() na cel� URL, proto�e URL je zde hodnotou HTML atributu. V tomto p��pad� prohl�e� nejd��ve odstran� speci�ln� znaky a pak zpracuje URL. PHP spr�vn� pochop� pos�lan� URL, proto�e jste data zak�dovali pomoc� urlencoded().

M��ete se v�imnout, �e symbol & v URL je nahrazen &amp;. P�esto�e to v�t�ina prohl�e�� oprav�. pokud na to zapomenete, nen� to v�dy mo�n�. Tak�e pokud v� URL nen� dynamick�, mus�te pou��t htmlspecialchars().

2. Zkou��m pou��t tag <input type="image">, ale prom�nn� $foo.x a $foo.y nejsou dostupn�. Kde jsou?

Kdy� odes�l�te formul��, lze nam�sto standardn�ho tla��tka pou��t obr�zek pomoc� tagu jako
<input type="image" src="image.gif" name="foo">
Kdy� u�ivatel klikne n�kde na obr�zku, p��slu�n� formul�� se ode�le na server s dv�ma prom�nn�mi nav�c: foo.x a foo.y.

Proto�e $foo.x a $foo.y jsou v PHP neplatn� n�zvy prom�nn�ch, jsou automaticky p�evedeny na $foo_x a $foo_y. Tzn. te�ky jsou nahrazeny podtr��tky.

3. Jak vytvo��m pole ("array") v HTML formul��i?

Aby v�sledky odesl�n� va�eho formul��e byly um�st�ny v poli (array), nazv�te elementy <input>, <select> nebo <textarea> t�mto zp�sobem:
<input name="MyArray[]">
<input name="MyArray[]">
<input name="MyArray[]">
<input name="MyArray[]">
V�imn�te si hranat�ch z�vorek po n�zvu prom�nn�, to je to, co z toho d�l� pole. M��ete seskupovat elementy do r�zn�ch pol� spojen�m stejn�ho jm�na s r�zn�mi elementy:
<input name="MyArray[]">
<input name="MyArray[]">
<input name="MyOtherArray[]">
<input name="MyOtherArray[]">
Toto produkuje dv� pole, MyArray a MyOtherArray, kter� budou zasl�na PHP skriptu. Je tak� mo�n� d�t do pol� specifick� kl��e:
<input name="AnotherArray[]">
<input name="AnotherArray[]">
<input name="AnotherArray[email]">
<input name="AnotherArray[phone]">
Pole AnotherArray bude nyn� obsahovat kl��e 0, 1, email a phone.

Pozn�mka: Specifikace kl�c� pol� je v HTML nepovinn�. Pokud kl��e nespecifikujete, pole bude vypln�no podle po�ad� element� ve formul��i. N� prvn� p��klad obsahuje kl��e 0, 1, 2 a 3.

Viz tak� Funkce pro pr�ci s poli a Prom�nn� z vn�j�ku PHP.

4. Jak z�sk�m v�echna data z HTML elementu pro v�cen�sobn� v�b�r?

Tag pro v�cen�sobn� v�b�r v HTML p��kazu umo��uje u�ivatel�m vybrat v�ce polo�ej ze seznamu. Tyto polo�ky se pos�laj� do handleru pro formul��. Probl�m je v tom, �e se zpracov�vaj� pod stejn�m jm�nem. Nap��klad:
<select name="var" multiple>
Ka�d� vybran� mo�nost p�ijde do handleru akce jako:
var=option1
var=option2
var=option3
Ka�d� volba tedy p�ep�e p�edchoz� obsah prom�nn� $var �e�en�m je pou��t "pole vytvo�en� v elementu formul��e". M�lo by se pou��t toto:
<select name="var[]" multiple>
V��e uveden� k�d ��k� PHP, �e m� prom�nnou $var zpracovat jako pole a ka�d� p�i�azen� hodnoty do var[] znamen� p�id�n� prvku do pole. Prvn� polo�ka se tedy stane prvkem $var[0], dal�� $var[1] atd. Funkci count() lze pou��t k ur�en�, kolik mo�nost� bylo vybr�no, a v p��pad� pot�eby lze se�adit pole funkc� sort().

Uv�domte si, �e pokud pou��v�te JavaScript, m��e p�id�n� [] do n�zvu elementu zp�sobit probl�my p�i pokusu odkazovat element jeho jm�nem. Tehdy pou�ijte ��selnou identifikaci elementu, nebo n�zev prom�nn� uzav�ete do apostrof� a pou�ijte ho jako indexaci do pole element�, nap��klad:
variable = documents.forms[0].elements['var[]'];



add a note add a note User Contributed Notes
PHP a HTML
Karen
05-Aug-2004 12: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 05: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
13-Jun-2004 11: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:



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 02: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 04: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:


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

[email protected]
davis at risingtiger dot net
09-Jan-2004 08: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 04: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 :)
03-Oct-2003 10: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 06: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 08: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).
josh at NO chatgris SPAM dot com
15-Jan-2003 10: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.

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

<?php
$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.)
martellare at hotmail dot com
26-Nov-2002 07: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 08: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="[email protected]">Bill Gates</option>
<option value="[email protected]">Bill Clinton</option>
<option value="[email protected]">Bart Simpson</option>
<option value="[email protected]">OJ Simpson</option>
<option value="[email protected]">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 04: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 10:30
I think '[' and ']' are valid characters for name attributes.


-> InputType of 'name' attribute is 'CDATA'(not 'NAME' type)


-> about CDATA('name' attribute is not 'NAME' type!)
...CDATA is a sequence of characters from the document character set and may include character entities...


--> about character entity references in HTML 4
([ - &#91, ] - &#93)

<Pou��v�n� PHPPHP a COM>
 Last updated: Thu, 15 Jul 2004
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2004 The PHP Group
All rights reserved.
This unofficial mirror is operated at: /
Last updated: Sun Nov 14 23:09:54 2004 Local time zone must be set--see zic manual page