Working with forms is one of the most important concepts in PHP because it allows users to interact with your website—submit data, login, register, upload files, and more. PHP processes form inputs using GET, POST, and REQUEST methods.
Let’s break it down in a clear and simple way.
1. How Forms Work in PHP
HTML forms collect data from the user and send it to a PHP script.
Basic HTML Form
<form action="process.php" method="post">
<label>Name:</label>
<input type="text" name="username">
<button type="submit">Submit</button>
</form>
When the user submits the form:
- The data goes to process.php
- PHP reads the data using
$_POST["username"]
2. Methods Used in Forms
a) POST Method
- Sends data securely (not visible in URL)
- Used for login forms, registration, file upload
$name = $_POST['username'];
echo "Hello, $name!";
b) GET Method
- Sends data in the URL
- Used for search queries, filters, page numbers
$search = $_GET['q'];
echo "You searched for: $search";
c) REQUEST Method
- Contains both POST and GET data
- Not recommended for sensitive data
$data = $_REQUEST['username'];
3. Validating Form Inputs
Always validate user input before using it.
if (empty($_POST['username'])) {
echo "Name is required!";
}
4. Sanitizing User Input
To prevent hacking attacks (XSS, SQL injection):
$name = htmlspecialchars($_POST['username']);
$name = trim($name);
5. Handling Multiple Inputs
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
echo "Name: $name <br>Email: $email";
}
6. Using Checkbox, Radio, Select Fields
Checkbox
$skills = $_POST["skills"]; // returns array
Radio
$gender = $_POST["gender"];
Select (Dropdown)
$country = $_POST["country"];
7. File Uploading in Forms
HTML:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="myfile">
<button type="submit">Upload</button>
</form>
PHP:
move_uploaded_file($_FILES['myfile']['tmp_name'], "uploads/" . $_FILES['myfile']['name']);
8. Form Handling Best Practices
✔ Always validate and sanitize user input
✔ Use POST for sensitive data
✔ Maximum upload size should be checked
✔ Use CSRF tokens for security
✔ Escape output using htmlspecialchars()
Conclusion
Forms allow users to interact with your PHP website, and PHP makes it easy to receive, validate, sanitize, and process form data. Mastering forms is essential for building login systems, admin panels, file uploads, and dynamic websites.
Citations
🔗 View other articles about PHP:
http://savanka.com/category/learn/php/
🔗 External PHP Documentation:
https://www.php.net/manual/en/
