Forms PHP - Practical Example

Learn how web forms work with PHP: from submission to processing


Descargar Formulario

How Does a Form Work in PHP?

1. The User Fills Out the Form

The user enters data into the fields of the form HTML:

  • Text fields for first name, last name, etc.
  • Select for predefined options
  • Textarea for long remarks

2. Sending to the Server

When clicking "Send", the data travels to the server:

<form action="accion.php" method="post">
    <!-- Campos del formulario -->
</form>

action: Indicates which file will process the data

method="post": The data is sent securely

3. PHP Processes the Data

The file accion.php receives and processes the information:

<?php
// Recoger datos del formulario
$nombre = $_POST['nombre'] ?? '';
$apellido = $_POST['apellido'] ?? '';

// Procesar y guardar datos
file_put_contents('log.txt', $registro, FILE_APPEND);
?>

4. Display the Result

Finally, a confirmation page is shown to the user with the processed data.

📝 Functional Example - Try it!

This is a real form you can try. Fill in the data and see how it's processed.

Contact Form

🔍 Form Code (formulario.php)

This is how the form is structured in HTML:

HTML structure of the Form

<!DOCTYPE html>
<html>
<head>
    <title>Formulario PHP</title>
</head>
<body>
    <form action="accion.php" method="post">
        <label>Nombre: <input type="text" name="nombre"/></label>
        <label>Apellido: <input type="text" name="apellido"/></label>
        <label>Correo: <input type="text" name="correo"/></label>
        <label>Teléfono: <input type="text" name="telefono"/></label>
        <label>Observaciones: <textarea name="observaciones"></textarea></label>
        <label>Provincia:
            <select name="provincia">
                <option value="provincia1">Toledo</option>
                <option value="provincia2">Guadalajara</option>
                <option value="provincia3">Ciudad Real</option>
                <option value="provincia4">Cuenca</option>
                <option value="provincia5">Albacete</option>
            </select>
        </label>
        <input type="submit" value="Enviar"/>
    </form>
</body>
</html>

Key Points of the Form:

  • action="accion.php": The data is sent to this file
  • method="post": Secure submission method
  • name="nombre": Identifies each field in PHP
  • required: Makes the field mandatory (HTML5)

⚙️ Processing Code (accion.php)

This is how PHP processes the received data:

accion.php File - Data Processing

<?php
// Verificar que se envió el formulario por POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // Recoger datos del formulario con valores por defecto
    $nombre = $_POST['nombre'] ?? '';
    $apellido = $_POST['apellido'] ?? '';
    $correo = $_POST['correo'] ?? '';
    $telefono = $_POST['telefono'] ?? '';
    $provincia = $_POST['provincia'] ?? '';
    $observaciones = $_POST['observaciones'] ?? '';

    // Mapear códigos de provincia a nombres legibles
    $provincias = [
        'provincia1' => 'Toledo',
        'provincia2' => 'Guadalajara',
        'provincia3' => 'Ciudad Real',
        'provincia4' => 'Cuenca',
        'provincia5' => 'Albacete'
    ];

    // Obtener fecha y hora actual
    $fecha = date('Y-m-d H:i:s');

    // Convertir código de provincia a nombre legible
    $provinciaLectura = $provincias[$provincia] ?? 'No seleccionada';

    // Crear línea de registro para el archivo
    $registro = "[$fecha] Nombre: $nombre $apellido | ";
    $registro .= "Correo: $correo | Teléfono: $telefono | ";
    $registro .= "Provincia: $provinciaLectura | Observaciones: $observaciones" . PHP_EOL;

    // Guardar en archivo de log (se crea automáticamente si no existe)
    file_put_contents('log.txt', $registro, FILE_APPEND);
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Confirmación de Envío</title>
    <style>
        /* Estilos para la página de confirmación */
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        
        .tarjeta {
            background-color: #000;
            color: #fff;
            width: 400px;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 8px 20px rgba(0,0,0,0.3);
        }
    </style>
</head>
<body>
    <div class="tarjeta">
        <h1>Información del Cliente</h1>
        <p><span class="label">Nombre:</span> 
           <?php echo htmlspecialchars($nombre . ' ' . $apellido); ?></p>
        <p><span class="label">Correo:</span> 
           <?php echo htmlspecialchars($correo); ?></p>
        <p><span class="label">Teléfono:</span> 
           <?php echo htmlspecialchars($telefono); ?></p>
        <p><span class="label">Provincia:</span> 
           <?php echo htmlspecialchars($provinciaLectura); ?></p>
        <div class="observaciones">
            <span class="label">Observaciones:</span><br/>
            <?php echo nl2br(htmlspecialchars($observaciones)); ?>
        </div>
    </div>
</body>
</html>

Functions PHP Important:

  • $_POST['nombre']: Accesses data from the form
  • htmlspecialchars(): Prevents XSS
  • nl2br(): Converts line breaks into <br>
  • file_put_contents(): Saves data to a file
  • date(): Gets the current date and time

📊 Complete Data Flow

Step by Step

  1. User fills out the form in formulario.php
  2. Data is sent via the POST to accion.php
  3. PHP processes data with $_POST
  4. Record is saved in the file log.txt
  5. Confirmation is shown to the user

Generated Files

  • formulario.php: Page with the form
  • accion.php: Processes and shows results
  • log.txt: File with all records (created automatically)

🎯 Expected Result

After submitting the form, you'll see a black card with your data and the file will be created/updated log.txt with a line like this:

[2024-01-15 14:30:25] Nombre: María García | Correo: maria@ejemplo.com | Teléfono: +34 600 123 456 | Provincia: Toledo | Observaciones: Me gusta mucho esta página educativa

🎓 For Students - Concepts to Learn

HTTP Methods

POST vs GET:

  • POST: Data is hidden, more secure, no size limit
  • GET: Data visible in the URL, less secure, character limit

Security in Forms

  • htmlspecialchars(): Escapes characters HTML
  • Validation: Always validate on the server
  • Fields required: Basic validation on the frontend

File Handling

  • file_put_contents(): Writes to files
  • FILE_APPEND: Adds content without deleting what exists
  • PHP_EOL: Line break compatible with any OS