我正在Wordpress中构建表单,我想增加一层安全性以防止垃圾邮件。
我通常采用这种方式:
header.php
<?php
session_start();
if (!isset($_SESSION['_token'])) {
$_SESSION['_token'] = md5(time());
}
if ($_POST) {
if (!isset($_POST['url']) || !empty($_POST['url'])) {
header('Location: https://website.com/');
exit;
}
if ($_SESSION['_token'] != $_POST['_token']) {
header('Location: https://website.com/');
exit;
}
$_SESSION['end'] = time();
$diff = ($_SESSION['end'] - $_SESSION['start']);
if ($diff < 1) {
header('Location: https://website.com/');
exit;
}
} else {
$_SESSION['start'] = time();
}
if (false === strpos($_SERVER['REQUEST_URI'], 'thank-you.php')) {
$bThankYou = false;
} else {
$bThankYou = true;
}
?>
form.php
<form method="post" action="#">
<input type="hidden" name="_token" value="<?= $_SESSION['_token']?>">
<input type="text" name="url" id="url" value="">
</form>
它通常有效。
但是现在我在WordPress环境中,由于某种原因,我无法修改header.php。
所以我必须以不同的方式构造代码。
基本上,我以短代码的形式创建此表单:
function.php
add_shortcode('req_form_landing' , 'render_req_form_landing' );
function render_req_form_landing($atts , $content){
$atts = shortcode_atts( array(
'btnsubmit_label' => 'SUBMIT',
) , $atts);
$content = (empty($content))? " " : $content;
extract($atts);
$html='
<form method="post" action="">
<input type="hidden" name="_token" value="'.$_SESSION["_token"].'">
<input style="display:none;" type="text" name="url" id="url" value="">
不是理想的,但有时世界是残酷的。无论如何,我的问题是,例如,如果要在处理表单的文件中添加会话:
process.php
<?php
session_start();
if (!isset($_SESSION['_token'])) {
$_SESSION['_token'] = md5(time());
}
if ($_POST) {
if (!isset($_POST['url']) || !empty($_POST['url'])) {
header('Location: https://website.com/');
exit;
}
if ($_SESSION['_token'] != $_POST['_token']) {
header('Location: https://website.com/');
exit;
}
}
我得到一个错误:
Cannot modify header information - headers already sent by
这是有道理的,但我不确定要如何解决,我可以更改输出缓冲:
<?php
if ($_POST) {
if (!isset($_POST['url']) || !empty($_POST['url'])) {
ob_start();
header('Location: https://website.com/');
ob_end_flush();
exit;
}
if ($_SESSION['_token'] != $_POST['_token']) {
ob_start();
header('Location: https://website.com/');
ob_end_flush();
exit;
}
}
但它可能行不通。
有什么想法吗?