PHP Contact Form: Server-side validation (minimal)
Never trust client-side JS-validate on the server.
Anti-spam note: add a honeypot field (hidden input) + basic rate limit by IP.
#php #webdev #security #forms
Never trust client-side JS-validate on the server.
<?php
// contact.php
header('Content-Type: application/json');
$in = filter_input_array(INPUT_POST, [
'name' => FILTER_SANITIZE_FULL_SPECIAL_CHARS,
'email' => FILTER_SANITIZE_EMAIL,
'message' => FILTER_SANITIZE_FULL_SPECIAL_CHARS,
'hp' => FILTER_UNSAFE_RAW, // honeypot
]);
if (!empty($in['hp'])) exit(json_encode(['ok'=>false])); // bot
$name = trim($in['name'] ?? '');
$email = trim($in['email'] ?? '');
$msg = trim($in['message'] ?? '');
if ($name==='' || $msg==='' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(422);
exit(json_encode(['ok'=>false,'error'=>'Invalid input']));
}
// TODO: mail() or SMTP here
exit(json_encode(['ok'=>true]));
Anti-spam note: add a honeypot field (hidden input) + basic rate limit by IP.
#php #webdev #security #forms