Longhorn PHP 2026 - Call For Papers

Tratar con formularios

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.

add a note

User Contributed Notes 3 notes

up
33
sethg at ropine dot com
22 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
0
cedstyler22 at gmail dot com
20 hours ago
<div>
            <label for="auswahl">Auswahl:</label>
            <select id="auswahl" name="auswahl" required>
                <!-- size="3" → alle sichtbar, ohne size → normales Dropdown -->
                <option value="Option1" selected>Option 1</option>
                <option value="Option2">Option 2</option>
                <option value="Option3">Option 3</option>
            </select>
        </div>

        <div>
            <fieldset>
                <legend>Mehrfachauswahl:</legend>
                <input type="checkbox" id="cb1" name="auswahl[]" value="Wert1" checked>
                <label for="cb1">Wert 1</label>
                <input type="checkbox" id="cb2" name="auswahl[]" value="Wert2">
                <label for="cb2">Wert 2</label>
                <input type="checkbox" id="cb3" name="auswahl[]" value="Wert3">
                <label for="cb3">Wert 3</label>
            </fieldset>
        </div>

        <div>
            <label>Anzahl:</label>
            <input type="radio" id="r1" name="anzahl" value="1" checked>
            <label for="r1">1</label>
            <input type="radio" id="r2" name="anzahl" value="2">
            <label for="r2">2</label>
            <input type="radio" id="r3" name="anzahl" value="3">
            <label for="r3">3</label>
        </div>

        <div>
            <label for="fest">Fester Wert:</label>
            <input type="number" id="fest" name="fest" value="1" readonly>
        </div>

    </fieldset>
    </div>

    <div>
    <fieldset>
        <legend>Sonstiges</legend>
        <div>
            <label for="bemerkung">Bemerkung:</label><br>
      
            <textarea id="bemerkung" name="bemerkung" rows="5" cols="90"></textarea>
        </div>
    </fieldset>
    </div>

    <div>
        <button type="submit" name="submit">Absenden</button>
    </div>

</form>
up
0
cedstyler22 at gmail dot com
21 hours ago
<?php
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Aufgabe 1</title>
</head>
<style>
    div {
        margin-top: 0.2rem;
        margin-bottom: 0.2rem;
    }
    .pflichtfeld {
        border: 2px solid red; 
    }
    legend {
        background-color: lightgray; 
    }
</style>
<body>

<h1>TITEL</h1>
<h2>UNTERTITEL</h2>
<p>Felder im roten Rahmen / mit grauer Legende sind Pflichtfelder.</p>

<form action="aufgabe1.php" method="POST">
    <div>
    <fieldset class="pflichtfeld">
        <legend>Gruppenname</legend>
        <div>
            <label for="name">Name:</label>
            <input type="text" id="name" name="name"
                   placeholder="Max Mustermann" required>
        </div>
        <div>
            <label for="datum">Datum:</label>
            <input type="date" id="datum" name="datum" required>
        </div>
        <div>
            <label for="email">E-Mail:</label>
            <input type="email" id="email" name="email"
                   placeholder="max@domain.de" required>
        </div>

      
        <div>
            <label for="bmi">BMI:</label>
            <input type="number" id="bmi" name="bmi"
                   min="10" max="100" step="0.1" required>
        </div>

      
        <div>
            <label for="pid">ID:</label>
           
            <input type="text" id="pid" name="pid"
                   pattern="[0-9]{5}"
                   placeholder="12345"
                   title="Bitte halten Sie sich an das vorgegebene Format: genau 5 Ziffern"
                   required>
        </div>
To Top