Setting a global flag in php, wordpress

I know there were many questions like this, and I’ve been trying the suggested solutions, but they don’t seem to work for me.

I’ve added captcha to wordpress site, which is being verified by making a GET request in jQuery to validate-captcha.php, and returns a message. Works like a charm.

Read More

On return I trigger a click of invisible ‘submit’ button.
To be sure the comment is not posted without captcha check, I need a global flag. I’m setting it in validate-captcha.php:

global $captchaFlag; //first line
...

} else {
    // Handle a successful verification
    global $captchaFlag; //overkill to make sure it IS global
    $captchaFlag = 1;
    echo ('true'.$GLOBALS['captchaFlag']); //echoes fine
}

Then on submit, I’ve set a filter in functions.php that should check captchaFlag and either submit a comment directly if flag = 1 or verify captcha if flag = 0 or doesn’t exist:

add_filter("preprocess_comment", "verify_comment_captcha");

function verify_comment_captcha($commentdata) {
    global $captchaFlag;
    echo("<script>console.log('PHP: ".json_encode($captchaFlag)."');</script>");
    echo("<script>console.log('PHP: ".json_encode($GLOBALS['captchaFlag'])."');</script>");
    return null;
}

But echoing global $captchaFlag; or $GLOBALS['captchaFlag'] on submit shows that the value is null even if it was already set to 1 by validate-captcha.php.

What am I doing wrong?

Related posts

1 comment

  1. Globals don’t persist across page loads, so that won’t work.

    You were on the right track using $_SESSION, however I suspect that wasn’t working for you because you need to call session_start(); before setting or accessing session variables.

Comments are closed.