Tratando Formulários

Uma das características mais fortes do PHP é o jeito como ele trata formulários HTML. O conceito básico que é importante entender é que qualquer elemento de formulário em um formulário irá automaticamente ficar disponível para você usá-los em seus scripts PHP. Por favor leia a seção Variáveis externas do PHP para mais informações e exemplos de como usar formulários com PHP. Aqui vai um exemplo:

Exemplo #1 Um simples formulário HTML

<form action="acao.php" method="POST">
 Seu nome <input type="text" name="nome" />
 Sua idade: <input type="text" name="idade" />
 <input type="submit">

Não há nada de especial neste formulário. É um formulário HTML comum sem nenhuma tag especial de qualquer tipo. Quando o usuário preencher este formulário e clicar no botão enviar, a página action.php é chamada. Neste arquivo nós teremos algo como este:

Exemplo #2 Imprimindo dados de nosso formulário

Oi <?php echo $_POST["nome"]; ?>.
Você tem <?php echo $_POST["idade"]; ?> anos.

Um exemplo de saída deste script seria:

Oi Thomas.
Você tem 18 anos.

É óbvio o que este script faz. Não há nada de mais nele. As variáveis $_POST["nome"] e $_POST["idade"] são automaticamente criadas para você pelo PHP. Antigamente nós usávamos a auto-global $_SERVER, agora nós simplesmente usamos a auto-global $_POST que contém todos os dados vindos do POST. Se você usar o método GET então nossas informações residirão na auto-global $_GET. Você também pode usar a auto-global $_REQUEST se você não se importa com o tipo de dados que vêm do seu formulário. Esta auto-global contém uma mescla de GET, POST, COOKIE e FILE. Veja também a função import_request_variables().

add a note add a note

User Contributed Notes 7 notes

sethg at ropine dot com
11 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.
wojciech dot fornal at gmail dot com
2 months 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.
Johann Gomes (johanngomes at gmail dot com)
4 years ago
Also, don't ever use GET method in a form that capture passwords and other things that are meant to be hidden.
2 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 for clarity]
mail at pheunix dot in
5 months ago
It's true, comments do not take up PROCESSING time, but they do take some PARSING time in case you are not using a compile cache of some kind.
jerry4u at foxmail dot com
10 months ago
the difference of method GET and POST is really important.
behnam jaza faza
1 year ago
The note above says:

"Also see the import_request_variables() function. "

But dont:

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
To Top