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

search for in the

Usando código antiguo en nuevas versiones de PHP> <Algo útil
Last updated: Fri, 20 May 2011

view this page in

Uso de Formularios

Otra de las características más importantes de PHP es que gestiona formularios 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 lea la sección del manual titulada Variables fuera de PHP para más información y ejemplos sobre cómo usar formularios HTML con PHP. Observemos un ejemplo:

Example #1 A simple HTML form

<form action="accion.php" method="post">
 <p>Su nombre: <input type="text" name="nombre" /></p>
 <p>Su edad: <input type="text" name="edad" /></p>
 <p><input type="submit" /></p>
</form>

No hay nada especial en este formularo, es solamente HTML sin ninguna clase de etiquetas especiales de ningún tipo. Cuando el usario rellena éste formulario y oprime el botón Submit, una página titulada action.php es llamada. En este archivo encontrará algo así:

Example #2 Printing data from our form

Hola <?php echo htmlspecialchars($_POST['nombre']); ?>.
Usted tiene <?php echo (int)$_POST['edad']; ?> años de edad.

Un ejemplo del resultado de esta secuencia de comandos puede ser:

Hola José. Usted tiene 22 años de edad.

Aparte de las funciones htmlspecialchars() y (int), debería ser obvio de que hace el código. htmlspecialchars() se asegura que todos los caracteres que son especiales en html sean codificados adecuadamente de manera que nadie pueda inyectar etiquetas HTML o Javascript en tu página web. El campo edad, como sabemos que es un número, podemos convertirlo en un integer que automáticamente se deshará de cualquier carácter no numérico. También puede hacer lo mismo con PHP con la extensión filter Las variables $_POST['nombre'] y $_POST['edad'] son establecidas automáticamente por PHP. Anteriormente hemos usado la superglobal $_SERVER y ahora estamos apunto de introducirte la superglobal $_POST que contiene todos los datos del POST. Dese cuenta que el método de nuestro formulario es POST. Si usa el método fuera GET entoces los datos del formulario estarían en la superglobal $_GET. en lugar de POST. En su lugar también puedes usar la superglobal $_REQUEST, si no le importa el tipo de datos enviados desde el formulario. Contiene toda la información de GET, POST y COOKIE. Vea también la función import_request_variables().

You can also deal with XForms input in PHP, although you will find yourself comfortable with the well supported HTML forms for quite some time. While working with XForms is not for beginners, you might be interested in them. We also have a short introduction to handling data received from XForms in our features section.



add a note add a note User Contributed Notes Uso de Formularios
Johann Gomes (johanngomes at gmail dot com) 12-Oct-2010 02:20
Also, don't ever use GET method in a form that capture passwords and other things that are meant to be hidden.
arnel_milan at hotmail dot com 29-Mar-2008 05:27
I was so shocked that some servers have a problem regarding the Submit Type Name and gives a "Not Acceptable error" or Error 406.

Consider the example below :

<form action="blah.php" method="POST">
  <table>
    <tr>
      <td>Name:</td>
      <td><input type="text" name="name"></td>
    </tr>
   
    <tr>
      <td colspan="2" align="center">
        <input type="submit" name="Submit_btn" id="Submit_btn" value="Send">
      </td>
    </tr> 
  </table>
</form>

This very simple code triggers the "Not Acceptable Error" on
PHP Version 5.2.5 and Apache 1.3.41 (Unix) Server.

However to fix this below is the right code:

<form action="blah.php" method="POST">
  <table>
    <tr>
      <td>Name:</td>
      <td><input type="text" name="name"></td>
    </tr>
   
    <tr>
      <td colspan="2" align="center">
        <input type="submit" name="Submitbtn" id="Submit_btn" value="Send">
      </td>
    </tr> 
  </table>
</form>

The only problem that took me hours to find out is the "_" in the Submit Button.

Hope this help!
SvendK 09-Nov-2006 04:02
As Seth mentions, when a user clicks reload or goes back with the browser button, data sent to the server, may be sent again (after a click on the ok button).

It might be wise, to let the server handle whatever there is to handle, and then redirect (a redirect is not visible in the history and thus not reachable via reload or "back".

It cannot be used in this exact example, but as Seth also mentions, this example should be using GET instead of POST
yasman at phplatvia dot lv 05-May-2005 07: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.
sethg at ropine dot com 01-Dec-2003 08: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.

 
show source | credits | stats | sitemap | contact | advertising | mirror sites