|
|
 |
Otra de las caracterÃsticas de PHP es que gestiona
formularios de HTML. El concepto básico que es importante
entender es que cualquier elemento de los formularios
estará disponible automáticamente en su
código PHP. Por favor refiérase a la sección
titulada Variables
fuera de PHP en el manual para más
información y ejemplos sobre cómo usar formularios
HTML con PHP. Observemos un ejemplo:
Ejemplo 2-6. Un formulario HTML sencillo <form action="accion.php" method="POST">
Su nombre: <input type="text" name="nombre" />
Su edad: <input type="text" name="edad" />
<input type="submit">
</form> |
|
No hay nada especial en este formularo, es HTML limpio sin ninguna
clase de etiquetas desconocidas. Cuando el cliente llena
éste formulario y oprime el botón etiquetado
"Submit", una página
titulada accion.php es llamada. En este
archivo encontrará algo asÃ:
Ejemplo 2-7. Procesamiento de información de nuestro formulario
HTML |
Hola <?php echo $_POST["nombre"]; ?>.
Tiene <?php echo $_POST["edad"]; ?> años
|
Un ejemplo del resultado de este script podrÃa ser:
Hola José.
Tiene 22 años |
|
Es aparentemente obvio lo que hace. No hay mucho más que
decir al respecto. Las
variables $_POST["nombre"]
y $_POST["edad"] son definidas
automáticamente por PHP. Hace un momento usamos la variable
autoglobal $_SERVER, ahora hemos introducido
autoglobal $_POST,
que contiene toda la información enviada por el
método POST. FÃjese en el
atributo method en nuestro formulario; es
POST. Si hubiéramos usado GET,
entonces nuestra información estarÃa en la variable
autoglobal $_GET. También
puede utilizar la autoglobal $_REQUEST si no le
importa el origen de la petición. Ésta variable
contiene una mezcla de información GET, POST y
COOKIE. También puede ver la función
import_request_variables().
add a note
User Contributed Notes
Uso de Formularios HTML
verisimilidude at sourceforge dot com
18-Jul-2006 01:44
> It is easier to create a link called
> /website/deleteuser.php?id=<userid> for each, where
> deleteuser.php contains the (pseudocode):
> $sql = "DELETE FROM usertable WHERE id = " . (int) $_GET['id'];
Never pass raw data from the user directly into a string that will be passed on to be executed by something else (in this case SQL). In this case there is no check that the id coming back was ever on the table being displayed - you have given the web user the ability to delete anyone just by editing the name of the page requested.
In this case the id is cast to an int at least. Without the cast it would be possible to inject ANY sql into the database by asking (for example) /website/deleteuser.php?id="0; select * from another_table;"
Joe
29-May-2006 03:52
Just wanted to add a note:
For beginners, it is wise to use the "GET" method in forms because you can see what is being sent between the server and the web browser.
For example, in the example above, if you change
<form action="action.php" method="post">
to <form action="action.php" method="get">
you would get something like...
http://www.myserver.com/action.php?name=A&age=B
in your web browser.
However, a good idea is to always change the "GET" to a "POST" because the user of the browser cannot change the contents of the information being sent from the form to the webserver.
In the example given above,
<form action="action.php" method="post">
Would just have,
http://www.myserver.com/action.php
As you can see, no information is visible to the user of the browser.
In other words, _GET and _POST, has a lot of advantage over one another. I personally use "POST" in everything so that the user of the page cannot "spam" it by continually sending information with GET.
Simply put, with "GET" the user can physically change the values that the server gets, whereas with the "POST" method, the user will have a hard time changing the information sent to the server.
For example, if you have a user login service, you definitely want to submit the form by a "POST" so that if someone wants to "change" the account to something like admin, then he would have a hard time doing so because he cannot directly change the information on the browser URL line and then simply send it like that everytime.
David
22-May-2006 09:20
Grant Floyd's suggestion (in a two-year-old comment) to use HTTP GET for destructive actions like deleting users is an extremely dangerous one. It's a basic rule of the Web that HTTP GET should *never* do anything destructive -- any web agent that prefetches URLs for caching, etc., could end up deleting all of your users by following the links in the document.
yasman at phplatvia dot lv
05-May-2005 12:18
[Editor's Note: Since "." is not legal variable name PHP will translate the dot to underscore, i.e. "name.x" will become "name_x"]
Be careful, when using and processing forms which contains
<input type="image">
tag. Do not use in your scripts this elements attributes `name` and `value`, because MSIE and Opera do not send them to server.
Both are sending `name.x` and `name.y` coordiante variables to a server, so better use them.
grant_floyd at yahoo dot not dot yohoo dot com
21-Apr-2004 09:54
Refering to the GET/POST usage in the HTML specification mentioned:
Although GET will normally be used for requesting information from a webserver the length of the URL is limited to a maximum number of characters. So if you have a form which submits lots of information and text selections you will have to use a POST.
Likewise, sometimes it doesn't make any sense to create a form with a POST method to do something to the server.
For example, if you have a website with a list of users and you want to select one of them to delete, each username could be a 'Delete user' link. It is easier to create a link called /website/deleteuser.php?id=<userid> for each, where deleteuser.php contains the (pseudocode):
$sql = "DELETE FROM usertable WHERE id = " . (int) $_GET['id'];
Finally, $_REQUEST is the simplest default retrieval method as it combines GET, POST and COOKIE information. One thing to be aware of is that it combines the information in an order of precedence defined by the server.
For example, if a website has a cookie with $username and you make up a POST form and use a variable '$username' you may get the $_POST['username'] value instead of the $_COOKIE['username'], causing you some confusion.
The order is defined on the server as 'variables_order'. This set the order of the EGPCS (Environment, GET, POST, Cookie, Server) variable parsing. The default setting of this directive is "EGPCS". So in the above example 'P' for POST comes before 'C' for COOKIE.
sethg at ropine dot com
01-Dec-2003 12:55
According to the HTTP specification, you should use the POST method when you're using the form to change the state of something on the server end. For example, if a page has a form to allow users to add their own comments, like this page here, the form should use POST. If you click "Reload" or "Refresh" on a page that you reached through a POST, it's almost always an error -- you shouldn't be posting the same comment twice -- which is why these pages aren't bookmarked or cached.
You should use the GET method when your form is, well, getting something off the server and not actually changing anything. For example, the form for a search engine should use GET, since searching a Web site should not be changing anything that the client might care about, and bookmarking or caching the results of a search-engine query is just as useful as bookmarking or caching a static HTML page.
| |
| | Citas célebres | En nuestros locos intentos, renunciamos a lo que somos por lo que esperamos ser. William Shakespeare Escritor inglés (1564 - 1613) | | Citas en tu mail | | ©Contenidos Gratis |
| Chiste de... Animales | | El toro asomado a la ventana | - Pero Marcial, ¿cómo estás así de vendado?
- Ya ves, anoche, que bebí hasta el agua de los floreros, y vi venir dos toros... y quise saltar por una ventana de las dos que veía...
- ¿y?
- Mala suerte. Salté por la ventana que no era, y me cogió el toro que sí era. | | Chistes en tu mail | | ©ContenidosGratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|