首页 > 解决方案 > 使用ajax在两个php函数之间发送数据

问题描述

我目前正在网站上进行用户验证。我要做的是要求用户输入凭据并按下“发送确认”按钮,然后使用某些东西(短信或信使)将代码发送给用户,并让用户将此代码插入字段并单击“确认”以检查它是否正确。我现在面临的问题是如何将正确的代码从一个 PHP 函数(我目前使用 ajax 调用)传递给另一个。出于明显的安全原因,我不能只通过 JavaScript 发送代码,但欢迎您证明我错了 :)。这是我拥有的 HTML:

<button type="button" onclick="send_sms()">Send verification</button><br>
    Code from the SMS: <input type="text" id="fi" value=""><br>
    <p id="res"></p>
    
    <button type="button" onclick="check_sms()">Check</button>
    
    <script>    
    function check_sms() {

      jQuery.post(
            ajax_object.ajax_url,
            {action: "confirm_sms",
             code: document.getElementById("fi").value
            },
            function( response ) {
                // showing the result of confirmation
                document.getElementById("res").textContent = response;
            }
      );
    }
    
    function send_sms() {
        jQuery.post(
            ajax_object.ajax_url,
            {action: "send_sms",
             phone: document.getElementById("phone").value
            },
            function( response ) {
                // temporarely showing the code in console (shold not be there )
                console.log("not an sms, but the code for now is " + response);
            }
        );
    }
    </script>

现在,在functions.php中我有:

add_action( 'wp_ajax_confirm_sms', 'confirm_sms' );

function confirm_sms() {
    $code = $_POST['code'];
    
    // yes, I know that it will not output anything after, but it is beside the point anyway.
    // and yes, I will not send the real code as the output of the function (just for testing)
    wp_send_json($_SESSION['real_sms_code']);
    if ($code != $_SESSION['real_sms_code']) {
        wp_send_json('The code is not correct, please, try again');
        return;
    }
    wp_send_json("Nice code, awesome balls!");
}


add_action( 'wp_ajax_send_sms', 'send_sms' );
function send_sms() {
    // my attempt at storing the code, not the same session as I suspected, but was worth a try
    $_SESSION['real_sms_code'] = strval(rand(100000, 999999));
    wp_send_json($_SESSION['real_sms_code']);
}

这里的问题是confirm_sms函数总是输出'None'(它应该是另一个函数设置的代码),我不知道如何解决这个问题。我正在考虑创建一个包含此代码的文件,但是

a) 不可靠

b)我无法(可靠地)识别代码属于哪个用户,因为这是在他们注册之前

c) 对于许多用户来说,这可能会很慢

必须有更好的方法来处理这个问题。

标签: javascriptphpajaxwordpress

解决方案


所以我发现了这个问题:我$_SESSION从某个地方复制了这个部分,但是那里的人从未提到你必须session_start();在 PHP 中的函数之前使用。现在它完美无缺。有点令人沮丧,因为有人没有发布整个代码,我失去了一天,请不要那样 :)


推荐阅读