【问题标题】:PHP redirect after POSTPOST后PHP重定向
【发布时间】:2021-12-04 00:49:37
【问题描述】:

我正在使用 google 登录,并且大部分时间都在那里。用户成功登录,我可以访问我的 mysql 用户表来查找用户记录。 在完成用户处理并设置 $_SESSION 变量后,我想从 POST 页面重定向回我的 index.php 页面。我知道 POST 页面正在执行,但重定向不起作用,我没有看到任何错误(例如“无法修改标头信息 - 标头已发送”。

login.php包含google登录按钮,调用includes/oauth.js中的js函数

...
    <script src="https://apis.google.com/js/platform.js" async defer></script>
    <script src="includes/oauth.js"></script>
</head>
<body>
    <div id="content">
    <div class="g-signin2" data-longtitle="true" data-onsuccess="onSignIn"></div>
...

onSignIn 函数负责登录过程并检索用户详细信息。它还准备包含身份验证令牌的 POST 调用

...
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'includes/oauth.php');
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send('idtoken=' + id_token);
...

includes/oauth.php 文件获取令牌,对其进行验证。获取 userId,在我的数据库中查找它并准备会话变量。此时,它应该重定向,但没有。我难住了。这是因为我在 POST 中使用了 XMLHttpRequest() 吗?

<?php
session_start();
...
if (isset($_POST['idtoken'])){
...
                $_SESSION["auth"] = true;
                $_SESSION["userId"] = $row['id'];
                $_SESSION["userName"] = $row['name'];
                header("Location: ../index.php");
                exit();
}
...

【问题讨论】:

  • 由于您使用的是 AJAX,重定向只会导致 index.php 的内容返回为 xhr.responseText,它不会让浏览器打开 URL。
  • 只有当您在表单提交后重定向时,浏览器才会打开新的 URL。
  • 我原以为这可能与xhr有关,实际上我在调试过程中确实注意到了xhr.response.Text中的网页内容。
  • 实际执行重定向需要哪些选项?
  • xhr.onreadystatechange函数中,使用window.location = "../index.php"

标签: php post redirect google-signin


【解决方案1】:

也许,页面是否继续加载/处理并且没有结束?我正在研究一个类似的 Cookie/post 相关问题,它可能是一个类似的解决方案。就我而言,我必须使用cookie_write_close(),因为我会设置取决于当前session_start() 上下文的cookie。在添加cookie_write_close() 之前,php 进程将保持打开状态,并且不会发生重定向加载。相反,页面会根据服务器超时设置超时。

【讨论】:

    【解决方案2】:

    我更新了includes/oauth.js文件如下:

    var xhr = new XMLHttpRequest();
        xhr.open('POST', 'includes/oauth.php');
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function() {
            window.location = "../index.php";
        xhr.send('idtoken=' + id_token);
    

    现在一切正常!

    【讨论】:

      猜你喜欢
      • 2019-06-21
      • 1970-01-01
      • 1970-01-01
      • 2015-11-04
      • 1970-01-01
      • 2011-10-11
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      相关资源
      最近更新 更多