Securing forms in PHP involves taking measures to prevent common web application attacks such as cross-site scripting (XSS), cross-site request forgery (CSRF), and SQL injection.
Here is a sample code on how to secure forms in PHP:
1- Sanitize user input
It is essential to sanitize user input to prevent malicious code from being injected into your database or displayed on your web page. This can be done using PHP’s filter_input() function.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
//...
}
?>
2- Use prepared statements for database queries
Prepared statements can prevent SQL injection attacks. They work by separating the SQL code from the user input.
<?php
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->bindParam(':email', $email);
$stmt->execute();
?>
3- Use CSRF tokens
CSRF attacks occur when a user is tricked into executing an action without their knowledge. To prevent this, you can use CSRF tokens. A token is generated and added to the form, which is then checked when the form is submitted.
<?php
session_start();
$token = bin2hex(random_bytes(32));
$_SESSION['token'] = $token;
?>
<form method="post">
<input type="hidden" name="token" value="<?php echo $token; ?>">
<!-- form fields -->
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!isset($_POST['token']) || $_POST['token'] !== $_SESSION['token']) {
die('Invalid CSRF token');
}
//...
}
?>
4- Use HTTPOnly and Secure cookies
To prevent session hijacking, you can set the HTTPOnly and Secure flags on your cookies. The HTTPOnly flag prevents cookies from being accessed by JavaScript, and the Secure flag ensures that cookies are only transmitted over HTTPS.
<?php
session_set_cookie_params([
'lifetime' => 3600,
'path' => '/',
'domain' => '.example.com',
'secure' => true,
'httponly' => true,
'samesite' => 'Strict'
]);
session_start();
?>
5- Preventing SQL Injection Attacks
SQL injection attacks are a type of injection attack where malicious SQL code is inserted into a database query. To prevent SQL injection attacks, the following code snippet uses prepared statements.
$stmt = $pdo->prepare("INSERT INTO users (name, email, message) VALUES (:name, :email, :message)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':message', $message);
$stmt->execute();
These are just a few measures you can take to secure your PHP forms. Depending on your application, there may be other security considerations to take into account.