I'm working with google sign-in and am mostly there. User successfully signs in and I can access my mysql user table to look up the user record. After I've completed the user processing and set the $_SESSION variables, I want to redirect from the POST page back to my index.php page. I know that the POST page is executing, but the redirect isn't working and I'm not seeing any errors (like "Cannot modify header information - headers already sent".
login.php contains the google sign-in button and calls a js function in includes/oauth.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>
...
The onSignIn function takes care of the sign-in process and retrieves the user details. It also prepares the POST call including the authentication token
...
var xhr = new XMLHttpRequest();
xhr.open('POST', 'includes/oauth.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('idtoken=' id_token);
...
The includes/oauth.php file takes the token, validates it. Gets the userId, looks this up in my database and prepares the session variables. At this point, it's supposed to redirect, but doesn't. I'm stumped. Is this due to my using XMLHttpRequest() for the POST?
<?php
session_start();
...
if (isset($_POST['idtoken'])){
...
$_SESSION["auth"] = true;
$_SESSION["userId"] = $row['id'];
$_SESSION["userName"] = $row['name'];
header("Location: ../index.php");
exit();
}
...
CodePudding user response:
Perfect! Thanks, @Barmar.
I updated the includes/oauth.js file as follows"
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);
All working properly now!
CodePudding user response:
(i do not have enough rep to comment, so I will edit this answer if I can figure it out)
but the redirect isn't working and I'm not seeing any errors (like "Cannot modify header information - headers already sent".
so what ends up happening?
Perhaps, does the page continue to load/process and it does not end? I was working on a similar Cookie/post related problem and it may be a similar solution. In my case, I had to use cookie_write_close()
because I would set cookies that would depend on the current session_start()
context. Before adding cookie_write_close()
the php process would remain open and the redirect load would not occur. Instead the page would time out based on the server timeout settings.