Beginner Fundamentals
PHP Forms
Forms are the main way users send data to a PHP application. You read that data with the superglobals and must handle it safely.
A simple form
<form method="post" action="welcome.php">
Name: <input type="text" name="name">
<input type="submit" value="Send">
</form>
Reading the data
In welcome.php, access the submitted value through $_POST.
<?php
$name = $_POST["name"] ?? "";
echo "Hello, " . $name;
Use $_GET instead when the form method is get.
Validating input
Never trust user input. Check that required fields are present.
<?php
if (empty($_POST["name"])) {
echo "Name is required";
} else {
echo "Welcome!";
}
Escaping output for safety
Use htmlspecialchars() before printing user data to prevent cross-site scripting (XSS) attacks.
<?php
$name = $_POST["name"] ?? "";
$safe = htmlspecialchars($name);
echo "Hello, " . $safe;
Key rules
- Always validate required fields
- Escape output with
htmlspecialchars() - Filter and sanitize before storing or using data