Back to course

Handling User Input with HTML Forms

PHP: The Complete 0 to Hero Bootcamp

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:

  1. action: Where to send the data (usually the current PHP file or another processing script).
  2. method: The HTTP method (GET or POST).

html

<label for="age">Age:</label>
<input type="number" id="age" name="user_age">

<button type="submit" name="submit_form">Submit</button>

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

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.