CakeFest 2024: The Official CakePHP Conference

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">
    <label for="name">Your name:</label>
    <input name="name" id="name" type="text">

    <label for="age">Your age:</label>
    <input name="age" id="age" type="number">

    <button type="submit">Submit</button>
</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 int 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 contém 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

User Contributed Notes 2 notes

up
105
sethg at ropine dot com
20 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
8
Johann Gomes (johanngomes at gmail dot com)
13 years ago
Also, don't ever use GET method in a form that capture passwords and other things that are meant to be hidden.
To Top