Tratar con formularios

Otra de las características más potentes de PHP es la forma de gestionar formularios HTML. El concepto básico que es importante entender es que cualquier elemento de un formulario estará disponible automáticamente en sus scripts de PHP. Por favor, lea la sección del manual sobre Variables desde fuentes externas para obtener más información y ejemplos sobre cómo usar formularios con PHP. Observemos un ejemplo:

Ejemplo #1 Un formulario HTML sencillo

<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 formulario. Es solamente un formulario HTML sin ninguna clase de etiqueta especial. Cuando el usuario rellena este formulario y oprime el botón de envío, se llama a la página accion.php. En este fichero se podría escribir algo así:

Ejemplo #2 Mostrar información de nuestro formulario

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

Un ejemplo del resultado de este script podría ser:

Hola José. Usted tiene 22 años.

Excepto las partes de htmlspecialchars() y de (int), debería ser obvio qué es lo que hace el código. htmlspecialchars() garantiza que cualquier carácter que sea especial en html se codifique adecuadamente, de manera que nadie pueda inyectar etiquetas HTML o Javascript en la página. El campo edad, ya que sabemos que es un número, podemos convertirlo a un valor de tipo integer que automáticamente se deshará de cualquier carácter no numérico. También se 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; arriba introdujimos la superglobal $_POST, la cual contiene todos los datos de POST. Observe que el método de nuestro formulario es POST. Si hubiésemos usado el método GET, nuestra información estaría en su lugar en la superglobal $_GET. También se podría usar la superglobal $_REQUEST, si no le preocupa la fuente de los datos solicitados. Contiene toda la información de los datos de GET, POST y COOKIE mezclada.

En PHP, también puede tratar con entradas de XForms; aunque probablemente al principio se sienta cómodo con los formularios de HTML, los cuales están ampliamente respaldados. A pesar de que trabajar con XForms no es para principiantes, podrían interesarle. Si es así, en la sección de características hay una pequeña introducción a la manipulación de datos recibidos desde XForms.

add a note add a note

User Contributed Notes 6 notes

up
172
sethg at ropine dot com
14 years ago
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.
up
2
Toasty_Pallate
21 days ago
It is worth noting that GET request parameters can be cached while POST request parameters are not. Meaning that if a password is GETted it is stored at various points on the way to the server (Your browser and anyone it's sharing info with, the people manning the firewall at the Org that is receiving the GET, the server logs, etc.)

While it is true that HTTPS encrypts the URL and GET request parameters, nothing guarantees that there is not a Web Application Firewall (that decrypts all traffic going into the Org for inspection) and is logging user info or that one will be implemented in the future at your org. Logs in plain-text are (hopefully) a LOT easier to compromise than a database of hashed passwords.

So if you're managing sensitive information, it's best to use POST.
up
75
Johann Gomes (johanngomes at gmail dot com)
7 years ago
Also, don't ever use GET method in a form that capture passwords and other things that are meant to be hidden.
up
12
nucc1
6 months ago
worth clarifying:

POST is not more secure than GET.

The reasons for choosing GET vs POST involve various factors such as intent of the request (are you "submitting" information?), the size of the request (there are limits to how long a URL can be, and GET parameters are sent in the URL), and how easily you want the Action to be shareable -- Example, Google Searches are GET because it makes it easy to copy and share the search query with someone else simply by sharing the URL.

Security is only a consideration here due to the fact that a GET is easier to share than a POST. Example: you don't want a password to be sent by GET, because the user might share the resulting URL and inadvertently expose their password.

However, a GET and a POST are equally easy to intercept by a well-placed malicious person if you don't deploy TLS/SSL to protect the network connection itself.

All Forms sent over HTTP (usually port 80) are insecure, and today (2017), there aren't many good reasons for a public website to not be using HTTPS (which is basically HTTP + Transport Layer Security).

As a bonus, if you use TLS  you minimise the risk of your users getting code (ADs) injected into your traffic that wasn't put there by you.
up
-87
wojciech dot fornal at gmail dot com
2 years ago
@sethg at ropine dot com

You're partially right. For many people, the difference between POST/GET is about whether data is sent as a URL query (GET) or as a HTTP request payload together with headers (POST) and in most cases it is used so with regards to that.

In case of forms the difference between GET and POST has more to do with convenience and the fact that both methods fit to certain use cases and not with the fact whether a some resource is created/changed on the server or not (eg. login forms use POST method mainly to not expose sensitive data in URL etc.). It all depends on the back-end implementation what really happens after GET or POST request is received.

GET is good if you want the request to be cacheable and/or bookmarkable. In most HTML form cases though, POST seems always better, especially when we deal with long data (eg. forum post).

To be strict about HTTP verbs, POST verb usually means creation of new resource while to update an existing resource, the PUT method is used (not applicable in case of HTML forms except some additional hidden "method" form fields).

Those who are not familiar with HTTP verbs shall dive into HTTP specs (RFC 2616, section "9 Method Definitions")  and read a bit about REST.
up
-131
Andy
5 years ago
Just a reminder about security: the chosen HTTP request verb (e.g. POST, GET) does not necessarily make the request "secure". Any information that is not transmitted over an encrypted channel (using SSL, i.e. HTTPS) is transmitted in plan text.

For secure transport of sensitive/private information over HTTP consider using SSL as this prevents eve's dropping of the information transmitted over HTTP.

[Edited by googleguy@php.net for clarity]
To Top