PHP / HTML form - shows data on the same page in Docker container, does not print

ยท

1 min read

Example of a PHP/HTML form that processes and displays the data on the same page within a Docker container:

<!DOCTYPE html>
<html>
<head>
    <title>Form Example</title>
</head>
<body>
    <?php
    // Check if form is submitted
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Retrieve form data
        $name = $_POST['name'] ?? '';
        $email = $_POST['email'] ?? '';

        // Display form data
        echo "<h2>Submitted Data:</h2>";
        echo "<p>Name: " . htmlspecialchars($name) . "</p>";
        echo "<p>Email: " . htmlspecialchars($email) . "</p>";
    }
    ?>

    <h2>Form Example</h2>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
        <label for="name">Name:</label>
        <input type="text" name="name" id="name" required><br>

        <label for="email">Email:</label>
        <input type="email" name="email" id="email" required><br>

        <input type="submit" value="Submit">
    </form>
</body>
</html>

In this example, the PHP code checks if the form is submitted ($_SERVER['REQUEST_METHOD'] === 'POST'). If it is, it retrieves the form data ($name and $email) using $_POST superglobal variables and displays the submitted data using echo.

The form itself is an HTML form with two input fields for name and email, along with a submit button. The action the attribute of the form is set to htmlspecialchars($_SERVER['PHP_SELF']) to submit the form to the same page.

When you run this code within a Docker container with PHP installed, you should be able to access the form, submit it, and see the submitted data displayed on the same page.

ย