我在wordpress中使用SESSIONS有问题。我环顾四周,但找不到任何答案。在另一篇关于stackaoverflow的帖子中也提出了类似的问题,但还没有答案。我按照本教程构建了自己的 FORM:在 5 分钟内构建您自己的 wordpress 联系表单。
问题所在
为了使我的表单更安全,我决定生成一个会话字符串,并将该字符串存储在 SESSION 全局数组中(以防止表单劫持)。我在发布表单时发送相同的字符串作为隐藏字段。比我比较这两个值。但是,在我看来,提交表单时,SESSION 与我在提交之前存储在 SESSION 数组中的表单不同。
function myfunction() {
ob_start();
$errors = array();
//deliver_mail();
if(isset( $_POST['cf-submitted'] ) ) {
if( $_POST['formtoken1'] !== $_SESSION['formtoken1'] ) {
$errors['token'] = '<div>The form submited is not valid.</div>';
//debug
echo $_SESSION['formtoken1'];//At this point, SESSION[formtoken1] should be same as the one we generated before FORM submit, but it is not!
}
if(empty($errors)) {
//No Errors! Send Email
}
}
$_SESSION['formtoken1'] = md5(uniqid(rand(), true));
$_SESSION['formtoken1'] = htmlspecialchars($_SESSION['formtoken1']);
echo '<form action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post">';
echo '<input type="text" name="formtoken1" id="formtoken1" value="'. (isset($_SESSION['formtoken1']) ? $_SESSION['formtoken1'] : '') . '" />';
echo '<p><input type="submit" name="cf-submitted" value="Send"></p>';
echo '</form>';
return ob_get_clean();
}
add_shortcode( 'my_contact_form', 'myfunction' );//Create shortcode
提交此表单时,它总是会产生错误,因为 SESSION 变量与 POST 变量不同。当我在本地xampp服务器上的wordpress之外测试相同的代码时,它可以工作。如果有人能帮助我,我会很高兴。我也尝试过脚本顶部的session_start(),但仍然是同样的问题。
经过一些试验,我意识到帖子标题显示在页面顶部。我在myfunction()中启动了ob_start()。因此,标题在 SESSION 开始之前就已输出。我更改了代码如下,它现在可以工作了。此解决方案的唯一问题是wordpress在每次页面加载时都会调用ob_start()。如果它在 myfunction() 中工作会更好,因为这意味着 ob_start() 仅在帖子中调用短代码时才执行。`
//Plugin Name: test form
ob_start(); //put this outside the myfunction()
if(!session_id() ) {
session_start();
}
function myfunction() {
$errors = array();
//deliver_mail();
if(isset( $_POST['cf-submitted'] ) ) {
if( $_POST['formtoken1'] !== $_SESSION['formtoken1'] ) {
$errors['token'] = '<div>The form submited is not valid.</div>';
//debug
echo $_SESSION['formtoken1'];//At this point, SESSION[formtoken1] should be same as the one we generated before FORM submit, but it is not!
}
if(empty($errors)) {
//No Errors! Send Email
}
}
$_SESSION['formtoken1'] = md5(uniqid(rand(), true));
$_SESSION['formtoken1'] = htmlspecialchars($_SESSION['formtoken1']);
echo '<form action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post">';
echo '<input type="text" name="formtoken1" id="formtoken1" value="'. (isset($_SESSION['formtoken1']) ? $_SESSION['formtoken1'] : '') . '" />';
echo '<p><input type="submit" name="cf-submitted" value="Send"></p>';
echo '</form>';
return ob_get_clean();
}
add_shortcode( 'my_contact_form', 'myfunction' );//Create shortcode`