Losing session after a javascript redirect - php

I have a html file basically calls a php file via ajax and if a login is successful, redirects the user to the index.php page via a redirect (window.location... etc.)
When the index.php loads it checks to see if a session variable is set and if not - redirects the user back to the login page. The problem is that even though the login is a success and the session variable has been set, it is no longer set when the index.php file is loaded. Please see image for overview of process.
The problem is that even though the login is successful and the $_SESSION variable was successfully set, after the javascript redirect the session is reported as being not set.
I do include the session_start() directive in both php files. Any advice would be much appreciated.
Sorry for not including code - here is the code I am using 1st - the ajax request and redirect from html page
function loginCompany(){
let email = 'test#test.com';
let pass ='124';
if ((email =='') || (pass==''))
{
alert('Please enter a user name or email and password');
$('#email').focus();
return;
}
$.ajax({
url: 'compAuth.php',
type: "POST",
async:true,
dataType: 'json',
data: {
email:email,
pass: pass,
userName : email
},
success: function (res) {
if (res){
if (res.status == 'Success')
{
window.location.replace('index.php');
return;
}
else {
console.log('not success : ');
if (res.status == 'Error') {
alert(res.description);
}
}
}
},// Success
error: function (res) {
}
});
}
Next is a snippet from Page B (the php script that sets the session and returns json results
$response = [ 'status' => 'Success'];
session_start();
$_SESSION['dbname'] = $row['dbname'];
echo json_encode($response);
And lastly - Page C which is called after a redirect from the initial HTML page (page A)
session_start();
if (!isset($_SESSION['dbname'])) {
header("location: login.php");
So its this last page (page C the index,php file) that does not see the $_SESSION variable as being set
Many thanks..
Paul.
P.S Also just to say that there is no cross-domain traffic - its all on the same domain :) Thanks.

After a couple of hours of destructive testing, it seems that the problem was with one of my required php files. It seems there was an error in one of the files but instead of generating an error - it just stopped the session variable from being set. Does not seem logical but at this point - I am just happy its working. I am new to this and assumed I was just "getting it wrong". Sorry for wasting peoples time and thanks for the feedback.
Paul.

Related

Handling redirection when session timeout via ajax

I have a view function which only logged in user can see. When clicking the view button, it will send an ajax request to PHP function and return back the result which then be displayed in the html. The issue is, if the user idle for too long, when they suddenly come and click the view button again, the display (where the ajax response supposed to be displayed) will show the login page instead of the requested data.
It was because the PHP session has expired. I want to prompt an alert to tell them about this timeout session and redirect them to the login page instead but I don't know how to do that cause I tried to console.log() the PHP session and it's still showing all of the session. I am convinced that this is something like a memory or a flash cache (not very sure).
QuickView = (pc_no) =>{
$.ajax({
type: 'get',
url: '<?= $ajax_url; ?>view-receipt/'+pc_no,
data: { pc_no:pc_no },
success: function(res){
console.log(<?= json_encode($this->session->userLogged); ?>)
<?php if($this->session->userLogged){ ?>
$('#receipt-inline-view').html(res);
<?php } else { ?>
if(alert('Your session has expired. Please re-login.')){
window.location.href = '<?= base_url(); ?>';
}
<?php } ?>
}
})
}
Based on the code above, the user session will be stored in $this->session->userLogged. After PHP timeout, it should be cleared. But from console at ajax there, it's still showing the session even after it gets cleared up. Hence, the redirection also cannot be triggered.

Redirect the user if the $_SESSION has expired in PHP

On each page I check if the user is connected (i.e.: if the user session is active or not).
validateSession();
function validateSession() {
if (!isset($_SESSION['CurrentLogged_USR_Id'])) {
header("Location: 'http://example.com');
}
}
It's working.
But if the user is on a page from a long time and the system needs to make an ajax call, the same check is done but do not redirect the user.
Why ?
I've include the validateSession() on my php page called by ajax but the redirection is not make.
Thanks.
You cannot redirect in PHP that is called through AJAX. Rather return a flag that identifies that session has expired and make redirection in JavaScript.
Below is sample code snippet.
$.ajax({
url: "urlToAJAX.php",
success: function(isSessionExpired){
if(isSessionExpired)
{
window.location = "http://example.com";
}
}});
You can follow this code.
Ajax
$.ajax({
url:..
type:..
success(data){
if(data == "SESSION_EXPIRED"){
window.location = "your-login-page";
}
}
});
In your PHP code, you have check if the session is available. If not echo the string SESSION_EXPIRED.

Is there a better way to check for expired SESSIONS when using JQuery?

I've only been using JQuery for a few weeks. And in this short time I've noticed that, when a SESSION expires, my Login page loads inside the already-loaded document. This was never an issue until I started using JQuery. So I'm thinking that, since I've rewritten all my documents for JQuery to make the calls to PHP, my lone SESSION check is being pulled into the JQuery PHP calls instead of redirecting to the login page. When it does this, a quick page refresh will send the user to the login page. But it sure looks cheesy.
So, my thinking on this (and I hope I'm wrong) is to put
if ($_SESSION["memberid"] == "") {
header("Location: wslogin.php");
exit();
}
inside every PHP block called by JQuery. Maybe this wld be what's now needed since I'm using JQuery. Before JQuery, all my work was inside <form> tags, and the pages reloaded with every action. And an ended SESSION was always sent to the login page. I'm not the best explainer in the world, but I hope someone understands this and has a solution. Thanks.
Send 401-Unauthorized status code from requested page if session expired. Then capture status code in your client AJAX call.
JavaScript
$.ajax({
data: {},
dataType: 'json',
success: function(data) {
// do whatever here
},
type: 'post',
url: 'load_data.php',
error: function(XMLHttpRequest, textStatus, errorThrown) {
// XMLHttpRequest.responseText has your json string
// XMLHttpRequest.status has the 401 status code
if (XMLHttpRequest.status === 401) {
location.href = 'login.php';
}
}
});
PHP
header('HTTP/1.1 401 Unauthorized', true, 401);
Reference
HTTP Status Codes
PHP Session, with php control your session
<?php
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 120)) {
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
header('location:logout.php');
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
if (empty($_SESSION['username'])) {
header('location:logout.php');
}
?>
Simply you may keep this on header of your template page so every time php check the session timing even you may improve this...

Providing Feedback After a Php Header Redirect

I have a html table in an application written with javascript (and jquery) and php. The contents of the table are stored in a MySql table.
When I want the user to add some data to the table, they click a button and a jquery ui dialog is shown, with a form for the user to fill out.
When the user fills out the form, they click save, and the form is submitted to a page of pure php, which saves the data to the table and then redirects to the original page with the table on, using
$url = BASE_URL . '/admin/pages/finance/pricing/pricing_schedule.php';
header('Location: '.$url); //Redirect to the right page
exit();
I am doing this because I don't want the message:
Confirm Form Resubmission - The page that you're looking for used information that you entered. Returning to the page might cause any action you took to be repeated. Do you want to continue?
to show should the user hit refresh for whatever reason.
However, because of the way I am doing this, I am struggling to provide a way to give feedback to the user should the save be unsuccessful.
When the user hits save in the jquery ui dialog box, the box is close when the form is submitted, so I can't provide feedback there because the error hasn't occurred yet.
When we are in the php page, as soon as we redirect back to the original page with the table on, any errors picked up are lost.
Can anyone offer any suggestions?
you could store any errors in the $_SESSION variable and print them out on the redirected page.
How about a simple GET parameter?
Something on the lines of:
header('Location: ' . $url . '?success=false&reason=blah');
And on that page at $url, you would first look for the value of $_GET['success']. If it is not "success", echo out additional HTML saying its not successful.
if ($_GET['success'] == "true") {
echo "<p>SUCCESS!</p>";
..
} else {
echo "<p>FAILED!</p>";
..
}
another idea is the transport of the message via the hash in the url:
if (isset($_POST['submit'])) {
...
header("Location: ".$_SERVER["REQUEST_URI"]."#".urlencode($msg));
...
}
Consider submitting your form through AJAX to avoid the page refresh.
Check out this tutorial: http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
Solution(Not Tested)
jQuery Code:
var form_data = $('#save_period_form').serialize(); alert(form_data);
$.ajax({
type: "POST",
url: "period_submit.php",
data: form_data,
dataType: 'html',
success: function(returninfo) {
if(returninfo=='1'){
alert('finish');
//will redirect to pricing schedule page after the user has pressed 'ok' on the alert popup.
window.location.assign('/admin/pages/finance/pricing/pricing_schedule.php');
} else {
alert('error occured');
}
}
});
PHP Code:
//Commented header redirection code because it's being done in the javascript code now.
//$url = BASE_URL . '/admin/pages/finance/pricing/pricing_schedule.php';
//header('Location: '.$url); //Redirect to the right page
//Assuming your save has been successful, we echo value '1'. Else echo something else..
echo '1';
exit();

redirecting an ajax processing page

I have a page that checks to see if the user logged in and if the user is not, uses an jQuery ajax call to a php processing page to get the information. But to get the information it has to redirect out to the 'login site' which sits on a different server, and the 'login site' then POSTs back the login information to the php page, and the php page turns the raw data into something the first page can understand.
Well at least that's what's suppose to happen.
What actually happens is that once the php processing page redirects I get a 302 error. I've tried going to the php page without the ajax call to it and it works fine, redirecting to the 'login site' and accepting the post back.
I can't remove the ajax call and just code the bounce into the first page because the page is html, unfortunately it has to stay that way, and html pages don't like POSTs to them and crash.
Below is the code with the ajax call...
if (Login == null) {
$.get("some_php_page.php", { }, function(data) {
if (data == "") {
} else {
//set login cookie;
}
});
}
Below is the php processing page...
if ($RefererServer != LoginServer) {
header( "Location: LoginServer/verify.php");
} else {
// send login information back
}
Anyone have any idea?
On the server side, you should return a json:
{ "success: false, "redirect": http://redirecturl.com }
On the client side, redirect is made by js
$.ajax({
// ....
success: function(response){
window.location = response.redirect;
}
});

Categories