Una de las características más poderosas de PHP es la forma en que maneja los formularios HTML. El concepto básico que es importante entender es que cualquier elemento de formulario estará automáticamente disponible para sus scripts PHP. Por favor, lea la sección del manual sobre Variables desde fuentes externas para obtener más información y ejemplos sobre el uso de formularios con PHP. Aquí hay un ejemplo de formulario HTML:
Ejemplo #1 Un formulario HTML sencillo
<form action="action.php" method="post"> <label for="name">Su nombre:</label> <input name="name" id="name" type="text"> <label for="age">Su edad:</label> <input name="age" id="age" type="number"> <button type="submit">Enviar</button> </form>
No hay nada especial en este formulario. Es un formulario HTML directo sin ninguna etiqueta especial. Cuando el usuario rellena este formulario y pulsa el botón de enviar, se invoca la página action.php. En este fichero escribiría algo como esto:
Ejemplo #2 Mostrar datos de nuestro formulario
Hola <?php echo htmlspecialchars($_POST['name']); ?>.
Tiene <?php echo (int) $_POST['age']; ?> años.Una salida de ejemplo de este script podría ser:
Hola Joe. Tiene 22 años.
Aparte de las partes htmlspecialchars() y
(int), debería ser obvio lo que hace esto.
htmlspecialchars() asegura que cualquier carácter que
sea especial en HTML se codifique correctamente para que la gente no pueda
inyectar etiquetas HTML o Javascript en su página. Para el campo de edad,
ya que sabemos que es un número, podemos simplemente
convertirlo a un
int que automáticamente eliminará cualquier carácter
adicional. También puede hacer que PHP haga esto automáticamente por usted
usando la extensión filter.
Las variables $_POST['name'] y
$_POST['age'] son establecidas automáticamente por PHP.
Anteriormente usamos la superglobal $_SERVER ; arriba
acabamos de introducir la superglobal $_POST que
contiene todos los datos POST. Observe cómo el método
de nuestro formulario es POST. Si hubiéramos usado el método
GET entonces nuestra información del formulario viviría
en la superglobal $_GET en su lugar.
También puede usar la superglobal $_REQUEST si no le
importa la fuente de sus datos de petición. Contiene la información
combinada de los datos GET, POST y COOKIE.
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.