browser ignoring header refresh from ajax response - php

In my javascript I have some ajax requests $.getJSON({...}) for various actions. I have a php app that handles these ajax requests. Before processing the actual request, my app first checks the session and in the case the user hasn't logged in yet, it sends a refresh signal back. Something like:
if (not logged in) {
header('Refresh: 0;');
}
else {
//process request
}
But the client doesn't actually refresh. Is there something I'm missing when it comes to AJAX requests and the http refresh header?

AJAX requests don't affect the browser until told to do so. Meaning, if i fetch a page using AJAX, it gets returned, maybe stored in a variable and that's it. It does not do anything after that. You need to parse the return data and act accordingly.
In your case, you might rather return something like JSON, have the client side parse what the return data meant, and act accordingly.
i tend to do something like:
{
"directives": {
//contains directives what to do first before parsing the data
"whatToDo" : "redirect"
},
"payload" : {
//actual page data
}
}

So the file your calling in your request contains the header('Refresh: 0;'); ? Because that has no effect at all, what i would do is if the user is not logged in return an unique string like so:
if (not logged in) {
echo "NOTLOGGEDIN";
}
else {
//process request
}
and then in your AJAX request check if they are logged in:
$.get("someURL", function(data) {
if(data == "NOTLOGGEDIN"){
//Do something
} else{
//Display data
}
});

Related

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...

Session expired during the ajax request in php

I have a problem that the session was expired and then I have clicked on a button which makes the ajax request, then on it holds & do nothing, in the console it displays as an error, if it is any other action then it redirects to login page but for the ajax it does nothing. Now what I need is that even on the ajax request it should get redirect to login page if the session gets expired. The main thing is that I have plenty of ajax calls in my application and I need to make a common script for all the ajax requests to get redirect to login page.
Please help me...
Call the server side file through ajax
Check for the session in the server side.
If session expired send response as session expired.
In the ajax success call back check the session expired data always.
If you found session expired value redirect to login using location.href.
Just a skeleton code below.
$.post('URL',{},
function (data) {
if (data.sessionexpired) {
location.href = 'login.php';
} else {
//Normal process
}
}
);
have the ajax request return an error code or the string error_go_home or something.
if the javascript that recieves that message gets that string, have the javascript redirect them home.

Login loading page

I have a php site where a user has the ability to login. Once they submit the POST data with their credentials they are taken to a page that initiates a session and checks the database. This process takes a long time before the user is ultimately redirected to the backend of the site. Durring this time the user stairs at a blank white page. I would like to show some kind of loading page, but when anything printable is on the page I get a header error due to the redirect.
How can I create a loading page? I understand that ajax is an option but is it my only option?
Update:
The PHP application is mainly taking a long time because each login is dependent on a foreign API that needs to be authorized as well as charging data that needs to be queried. I am not trying to mask something I can easily fix, I am trying to create a better user interface.
The login process takes ~10 seconds.
Well, the easy way to handle this is as follows:
Once a user pressed loging, using javascript, hide the login button, inject some ajaxloader gif, than send an AJAX request with the login credentials, salt it properly, log the user in, post the response as JSON, and intercept that response, and in case of success - do redirect, incase of failure - print appropriate message.
some code:
login-handler.php
$user = new user();
if ($user -> login($_POST['uid'], $_POST['password'], $_POST['whatever']){
$response['type'] = 'success';
}
else{
$response['type'] = 'failure';
}
echo json_encode($response);
js-login.js
$("#login").click(function(){
// verify that user put user name, password and whatever, hide button and show ajax loader
$.get("login-handler.php", {user: user, password: password}, function(data){
if (data.type == "success"){
window.location = "http://example.com/new/location/whatever";
}
else{
//print message
}
}, "JSON");
});
EDIT: but I'd like to join the other folks and consider using a faster/different API, as 10 secs loading time is utterly ridiculous, unless it is for yourself, in which case - knock yourself out.
There is a classic trick around this:
Set the target of the login form to a (invisible) iframe, but in it just set a variable to a redirection URL
On submit set the div carrying the username/password to .style.display='none', then set a already loaded "please wait" div to .style.display='block'
When the iframe finally loads use document.getElementById('myiframe').contentWindow.VarName to get the URL and write it to location.href

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;
}
});

Detect whether the browser is refreshed or not using PHP

I want to detect whether the browser is refreshed or not using PHP, and if the browser is refreshed, what particular PHP code should execute.
When the user hits the refresh button, the browser includes an extra header which appears in the $_SERVER array.
Test for the refresh button using the following:
$refreshButtonPressed = isset($_SERVER['HTTP_CACHE_CONTROL']) &&
$_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
If the page was refreshed then you'd expect two requests following each other to be for the same URL (path, filename, query string), and the same form content (if any) (POST data). This could be quite a lot of data, so it may be best to hash it. So ...
<?php
session_start();
//The second parameter on print_r returns the result to a variable rather than displaying it
$RequestSignature = md5($_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING'].print_r($_POST, true));
if ($_SESSION['LastRequest'] == $RequestSignature)
{
echo 'This is a refresh.';
}
else
{
echo 'This is a new request.';
$_SESSION['LastRequest'] = $RequestSignature;
}
In an AJAX situation you'd have to be careful about which files you put this code into so as not to update the LastRequest signature for scripts which were called asynchronously.
<?php
session_start();
if (!isset($_SESSION["visits"]))
$_SESSION["visits"] = 0;
$_SESSION["visits"] = $_SESSION["visits"] + 1;
if ($_SESSION["visits"] > 1)
{
echo "You hit the refresh button!";
}
else
{
echo "This is my site";
}
// To clear out the visits session var:
// unset($_SESSION["visits"]);
?>
If you mean that you want to distinguish between when a user first comes to the page from when they reload the page check the referrer. In php it is: $_SERVER["HTTP_REFERER"]. See if it is equal the page your script is running on. It may be the case that the client doesn't provide this information, if that happens you could set a cookie or session variable to track what the last requested page was.
To prevent duplicate form processing when a user hits the browser refresh or back button, you need to use a page instance id session variable, and a hidden form input that contains that variable. when the two don't match, then the user has refreshed the page, and you should not reprocess the form. for further details, see:
https://www.spotlesswebdesign.com/blog.php?id=11
If someone refreshes a page, the same request will be sent as the previous one. So you should check whether the current request is the same as the last one. This can be done as follows:
session_start();
$pageRefreshed = false;
if (isset($_SESSION['LAST_REQUEST']) && $_SERVER['REQUEST_URI'] === $_SESSION['LAST_REQUEST']['REQUEST_URI']) {
if (isset($_SERVER['HTTP_REFERER'])) {
// check if the last request’s referrer is the same as the current
$pageRefreshed = $_SERVER['HTTP_REFERER'] === $_SESSION['LAST_REQUEST']['HTTP_REFERER'];
} else {
// check if the last request didn’t have a referrer either
$pageRefreshed = $_SERVER['HTTP_REFERER'] === null;
}
}
// set current request as "last request"
$_SERVER['LAST_REQUEST'] = array(
'REQUEST_URI' => $_SERVER['REQUEST_URI'],
'HTTP_REFERER' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null
);
I haven’t tested it but it should work.

Categories