28. Handling User Input with HTML Forms
To capture data from a user, we use HTML forms and process that data using PHP superglobals.
Creating the HTML Form
The form must specify two attributes:
action: Where to send the data (usually the current PHP file or another processing script).method: The HTTP method (GETorPOST).
html
<!-- index.php --> <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <label for="username">Username:</label> <!-- The 'name' attribute determines the key in $_POST or $_GET --> <input type="text" id="username" name="username" required><label for="age">Age:</label>
<input type="number" id="age" name="user_age">
<button type="submit" name="submit_form">Submit</button>
</form>
Processing the Form Data (POST Example)
We check if the form was submitted (e.g., by checking if the submit button key exists in $_POST).
php
<?php // Check if the form was submitted using the POST method if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Check if the required fields exist if (isset($_POST['username']) && isset($_POST['user_age'])) { $username = $_POST['username']; $age = $_POST['user_age']; echo "Thank you, $username!"; echo "<br>Your age is $age."; } else { echo "Please fill in all required fields."; } } ?>Note: We use $_SERVER['PHP_SELF'] to submit the form back to the same script for processing, which is a common pattern.