As Pete said the Referer is really only useful for logging as it's client side and shouldn't be trusted. In fact it's incredibly easy to spoof the referer with any of the modern browsers.
You could have a look at using PHP's built in sessions as a crude way to test that the user submitted the form from your website. Basically what you'd do is initialise a session and when the user loads the form, putting some unique values into it, say a randomly generated hash, their IP address and browser user-agent string and then when the form is submitted retrieve those values from the session and check them against the new data received from the client. If they don't validate, send them back to the form.
It won't be totally secure, but it will help prevent other websites from submitting data to your form directly.
Something like this would work:
php code: <?php
// Our array of valid field names
$valid_post_fields = array('name', 'email', 'subject', 'message');
// Initialise the session.
session_start();
// Browser user-agent string
if (isset($_SERVER['HTTP_USER_AGENT'])) {
$http_user_agent = trim($_SERVER['HTTP_USER_AGENT']);
}else {
$http_user_agent = '';
}
// Client IP Address.
if (isset($_SERVER['REMOTE_ADDR'])) {
$remote_addr = $_SERVER['REMOTE_ADDR'];
}else {
$remote_addr = '';
}
// Get the session ID
$session_id = session_id();
// Check for form post
if (isset($_POST['submit'])) {
// Generate the hash.
$check_hash = md5($http_user_agent. $remote_addr. $session_id);
// Validate the session
if (isset($_SESSION['hash']) && $_SESSION['hash'] == $check_hash) {
// Get the post data and validate the fields.
$message = '';
foreach ($_POST as $key => $value) {
if (in_array($key, $valid_post_fields)) {
$message.= $fieldname . ": ". $value. "\r\r";
}
}
// Send the email
mail('me@mydomain.com', 'Email form doohicky', $message);
}
// Once you're done sending the email, generate a new session ID
session_regenerate_id();
// Finally redirect them somewhere, so the session is reset.
header('Location: form.php');
exit;
}
// Save the hash to the session
$_SESSION['hash'] = md5($http_user_agent. $remote_addr. $session_id);
// Put the code here to display the form and don't forget to update
// the valid_post_fields array for each field you add.
?> |