如果用户请求(GET)联系站点,我将设置会话令牌。提交表单后,我将令牌与表单中的令牌进行比较,但是我设置的令牌为空。这是我的代码:
<?php
session_start();
function debug_to_console($data)
{
$output = $data;
if (is_array($output)) {
$output = implode(',', $output);
}
echo "<script>console.log( 'Debug Objects: " . $output . "' );</script>";
}
//response generation function
$response = "";
function valid_spam_prevention($rob_email, $rob_website, $rob_phone)
{
debug_to_console($_POST['token']);
debug_to_console($_SESSION['royce']); // always empty
/* Please check me what is wrong with me
if ($_SESSION['token'] !== $_POST['token']) {
debug_to_console("Token false");
return false;
}
*/
if (empty($rob_email) && empty($rob_website) && empty($rob_phone)) {
return true;
}
return false;
}
//user posted variables
$name = $_POST['message_name'];
$email = $_POST['message_email'];
$message = $_POST['message_text'];
// rob posted variables
$rob_email = $_POST['email'];
$rob_website = $_POST['website'];
$rob_phone = $_POST['phone'];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (valid_spam_prevention($rob_email, $rob_website, $rob_phone)) {
unset($_SESSION['royce']);
// validate email and send etc
} elseif ($_POST['submitted']) {
// missing content error
}
} else {
// user request site with GET
$token = bin2hex(random_bytes(32));
$_SESSION['royce'] = $token;
}
?>
表单代码:
<form action="/contact" method="post">
<input type="hidden" name="token" value="<?php echo (isset($_SESSION['token'])) ? $_SESSION['token'] : ''?>">
<div>
<label for="message_name">Name</label>
<input id="message_name" name="message_name" type="text" value="<?php echo esc_attr($_POST['message_name']); ?>">
</div>
<div>
<label for="message_email">Mail</label>
<input id="message_email" name="message_email" type="email" value="<?php echo esc_attr($_POST['message_email']); ?>">
</div>
<div>
<textarea id="message_text" name="message_text"><?php echo esc_textarea($_POST['message_text']); ?></textarea>
</div>
<input id="email" name="email" type="email" autocomplete="false">
<input id="website" name="website" type="text" autocomplete="false">
<input id="phone" name="phone" type="text" autocomplete="false">
<button type="submit">Send</button>
</form>
对此我有何建议?
PHP版本:7.0.30