Handling form submissions with PDO prepared statement, and data filtering
PHP
<?php
if (filter_has_var(INPUT_POST, 'submit')) {
// validate and sanitize
/* ========================================================================================== */
$filters = array(
'blockspam' => FILTER_SANITIZE_STRING,
'cc_me' => FILTER_VALIDATE_BOOLEAN,
'ip_address' => FILTER_VALIDATE_IP,
'firstname' => FILTER_SANITIZE_STRING,
'lastname' => FILTER_SANITIZE_STRING,
'email' => FILTER_VALIDATE_EMAIL,
'company' => FILTER_SANITIZE_STRING,
'message' => array(
'filter' => FILTER_SANITIZE_STRING,
'flags' => FILTER_FLAG_NO_ENCODE_QUOTES
)
);
$input = filter_input_array(INPUT_POST, $filters);
$cc_me = $input['cc_me'];
$ip_address = $input['ip_address'];
$firstname = $input['firstname'];
$lastname = $input['lastname'];
$email = $input['email'];
$company = $input['company'];
$message = $input['message'];
if ($email == false) { echo '<pre>please use a valid email address.</pre>'; exit; }
if (!empty($blockspam)) { echo '<pre>message not sent, may be spam.</pre>'; exit; }
else { $blockspam = 'passed'; }
$blockspam_URL = '[url=';
if (strpos($message, $blockspam_URL) !== false) { echo '<pre>message not sent, please do not use [url= ]. </pre>'; exit; }
// connect to mysql database
/* ========================================================================================== */
$dbh = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$stmt = $dbh->prepare("INSERT INTO web_contact VALUES (?,?,?,?,?,?,?,?,NOW())");
$stmt->execute(array($entry_id, $blockspam, $ip_address, $firstname, $lastname, $email, $company, $message));
$dbh = null;
header('Location: /message.php?message=sent');
} // end if
?>