
Using forms in web applications is very common, and creating secure and user-friendly forms with PHP is essential.
In this article, we’ll demonstrate how to perform form validation and secure data handling using PHP with a practical example.
1. A Basic HTML Form
Let’s create a simple form that collects the user’s name, email, and message:
PHP
session_start();
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
HTML
<form action='process.php' method='post'>
<input type='hidden' name='csrf_token' value='<?php echo $_SESSION['csrf_token']; ?>'>
<label for='name'>Name:</label>
<input type='text' name='name' id='name' required>
<label for='email'>Email:</label>
<input type='email' name='email' id='email' required>
<label for='message'>Message:</label>
<textarea name='message' id='message' required></textarea>
<button type='submit'>Submit</button>
</form>
2. Handling Form Data with PHP
The following PHP code securely processes the submitted form data:
PHP
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die('Invalid CSRF token!');
}
$name = htmlspecialchars(trim($_POST['name']));
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = htmlspecialchars(trim($_POST['message']));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo 'Invalid email address!';
} else {
echo 'Thank you, your message has been received.';
// You can save to a database or send an email here.
}
}
3. Security Measures
- CSRF Protection: Include a CSRF token in forms to prevent forged requests.
- XSS Protection: Sanitize user inputs using
htmlspecialchars()
. - SQL Injection Protection: Use PDO with parameterized queries for database operations.
Related Articles

Reusable PHP Functions for Various Projects
0 Comments
Comments ()
No comments yet. Be the first to comment!