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 irá automaticamente ficar disponível para 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 de formulário HTML:

Exemplo #1 Um simples formulário HTML

<form action="action.php" method="post">
 <p>Your name: <input type="text" name="name" /></p>
 <p>Your age: <input type="text" name="age" /></p>
 <p><input type="submit" /></p>
</form>

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

Exemplo #2 Imprimindo dados de nosso formulário

Hi <?php echo htmlspecialchars($_POST['name']); ?>.
You are <?php echo (int)$_POST['age']; ?> years old.

Um exemplo de saída deste script seria:

Hi Joe. You are 22 years old.

Para além de htmlspecialchars() e (int), deve ser óbvio o que o script faz. htmlspecialchars() transforma caracteres que sejam especiais no HTML na sua forma codificada, de forma que não seja possível injetar tags HTML ou JavaScript em sua página. O campo age (idade), por ser um número, podemos simplesmente converter para um integer que automaticamente eliminará qualquer caractere estranho. Você também pode fazer o PHP automaticamente fazer isso utilizando a extensão filter. As variáveis $_POST['name'] e $_POST['age'] são criadas automaticamente pelo PHP. Anteriormente utilizamos a superglobal $_SERVER; acima mostramos que a superglobal $_POST contem todos os dados POST. Perceba como o method (método) do formulário é POST. Se fosse utilizado o método GET então os dados do formulário acabariam na superglobal $_GET. Você também pode utilizar a superglobal $_REQUEST, se não se importar qual a origem do dado enviado. Ela conterá os dados mesclados de origens GET, POST e COOKIE.

Você também pode utilizar XForms no PHP, embora se sinta confortável com os formulários HTML clássicos por um bom tempo. Embora trabalhar com XForms não seja para iniciantes, você pode se interessar por eles. Há uma seção com uma rápida introdução sobre manipular dados recebidos de XForms no manual.

add a note add a note

User Contributed Notes 5 notes

up
157
sethg at ropine dot com
13 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
63
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
4
nucc1
5 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
-74
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
-108
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