PHP Form Handling
The PHP superglobals $_GET and $_POST are used to collect form-data.
1. Simple HTML Form
Here is an example of a simple HTML form with two input fields and a submit button:
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
2. Handling the Data (POST)
When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables.
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
3. GET vs. POST
-
GET:
- Parameters remain in browser history because they are part of the URL.
- Can be bookmarked.
- NEVER use GET for sensitive data (passwords).
- Note:
$_GETis an array of variables passed to the current script via the URL parameters.
-
POST:
- Parameters are not saved in browser history.
- Cannot be bookmarked.
- Used for sending sensitive data.
- Note:
$_POSTis an array of variables passed to the current script via the HTTP POST method.
4. Basic Security
When processing form data, it is crucial to validate and sanitize the input to prevent security vulnerabilities like Cross-Site Scripting (XSS).
Use htmlspecialchars() to convert special characters to HTML entities.
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);