issue to set up session value in iframe - php

I am using joomla 1.5. I have a separate code which is in the same domain but in an another folder. I am accessing that folder within my joomla code by making use of iframe. Now I have to send the session value from joomla application to iframe and I am doing that by the following code.
echo '<iframe src="https://localhost/demo/quiz/quiz_main.php?u_d='.$user->id.'" width="910" height="885" style="background-color:transparent"></iframe>';
where $user->id is the registered user'd id and obviously this page will open if user logs in.
Then in the quiz_main.php page I am checking the value of u_d and according to that I am controlling the system.
Now the problem is suppose, I opened two tabs in the same browser with the same url and log in with same user id. Now log out from one tab. Then go to the other tab. User can perform any action for that small application which is running inside the iframe, until the page is not refreshed . But it should not be.
Please help me how to fix this issue.

You have to perform the check server side anyway, so in quiz_main.php you'll need something like
<?php
if(!user_is_logged_in())
// Redirect to login
?>
To prevent the user from performing any actions that will affect data on the server.
You can also do a check client side using JavaScript. You can poll the server every n seconds to check if the user still is logged in, and if not redirect the user to the appropriate page.
Example below with jQuery
function logged_in() {
$.ajax({
url: '/logged_in.php',
type: 'post',
success: function(data) {
data = $.parseJSON(data);
if(data['logged_in'] != true)
window.location('login.php');
else
setTimeout('logged_in()', 5000); // calling itself in 5 seconds.
}
});
}
$(document).ready(function() {
logged_in(); // Calling first time when the document is ready.
});
Just a rough sketch on how this could be done. You'll need a logged_in.php to handle to your request of course.

Related

wordpress losing the session on page refresh

I'm trying to develop a plugin for the wordpress and i'm having a small issue with the session. I have created my own login page for my plugin and when user puts his username/password and press the login button an ajax request sends the data to a function to check if user details are correct or not. The function that the ajax is calling is stored inside my index.php of my plugin. Using the $_SESSION in the function that ajax is calling, i can print the variable that I want,which has been set inside another file. Then if the data are correct the ajax reloads the page. When the page is been reloaded the session no more exist. Does anyone knows how i can solve this problem? I implemented the plugin on a localserver which was working fine, but when i uploaded the project on a subdomain on a server, it stopped to working.
AJAX code
success: function(data) {
console.log(data);
if (data !='')
{
var obj = $.parseJSON(data);
if (obj.status == "ok")
{
location.reload();
}
}
Thank you
Have you tried using the .RememberState function with your ajax call? Typically this might be applied to a form (so if the form is partially filled out and a user refreshes the page their changes are preserved), but in theory I don't see why you couldnt use it on the document itself. Check out this link it might explain it more clearly
http://shaneriley.com/jquery/remember_state/
You'd want to do this before the call, and in the success callback, you should be able to use this RememberState to return to the active session you had before. If this isn't what you're referring to I apologize for misinterpreting your question.

Allow access to PHP file only through ajax on local server

I have a website that needs to increment values in a database based upon user interaction. When users click a button a php script is called that increments the value. I'd like to protect this script from being accessed by outside scripts. Currently a user could write their own web page with a javascript function that hits the same php file repeatedly to blow up the value in the database.
Here's my jquery code that does the incrementing:
jQuery(function(){
$('.votebtn').click(function(e){
var mynum = $(this).attr('id').substring(0,5);
$.ajax({
url:"countvote.php",
type:"GET",
data: {
thenum:mynum
},
cache: false,
success:function(data) {
alert('Success!');
}
}
});
});
});
How would I go about making it so that only a call from ajax/jquery on the local server can access 'countvote.php'? If that's not the correct way to go about it, I'm open to any suggestion that will prevent my php script from being abused by outside scripts.
The solution needs two steps.
Firstly the ajax file must allow access only in ajax request with this code.
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!IS_AJAX) {die('Restricted access');}
Secondly the ajax file has access in the name of file that call it with command $_SERVER['HTTP_REFERER'].
So you can restrict access only in the host server.
$pos = strpos($_SERVER['HTTP_REFERER'],getenv('HTTP_HOST'));
if($pos===false)
die('Restricted access');
Maybe the code can work only with the second part
You can check if $_SERVER['HTTP_X_REQUESTED_WITH'] equals xmlhttprequest, but it's not a reliable method to determine whether a request is an AJAX request or not, there is always a way to get around this. But it protects you from random hits like wrongly entered urls, crawlers etc.
Theres not really a 100% method of doing so. AJAX requests are always going to come from a client. Use POST requests instead of GET and that will help deter any issues but not completely stop them and in your php, just drop all get requests.
I am not sure if this will work, but whats about settings an API key on eg. index.php into a $_SESSION variable, afaik this cannot be visible to the user, unless you do it manually, then in the restricted php file, check the $_SESSION['VOTEAPIKEY'] or whatever

Redirect website from within frame PHP

I have a web page, let's call it main.php which displays an image of football field and some players distributed on the field. However, that page uses list.php as a right side frame that loads a list of players.
What happens is, when the user clicks on a player on the field (main.php), let's say on the image of the Goal Keeper (GK), a list of GKs from world wide teams will load in right list fram (list.php). This is by using ajax.
So far we are good.
The current situation is, when session times out and the user clicks on a player from the field, the list on the right does not load, instead, list of players disappears from the list and a message says "Please login" is displayed on the right side frame (list.php)
The objective is, when session times out I want the whole website to redirect to the main page index.php
The problem is, I already put the redirecting code just before the code that is responsible of displaying the message "Please login". But what happened is, the redirection happens from within the frame, so i ended up having main.php displaying the field, and list.php displaying the main page!
Here's the code I added.
$user_id = NSession::get('user_id');
if (!isset($user_id))
{
NSession::removeall();
General::Redirect('index.php');
}
They are using Smarty. and btw, I added the same code to top of main.php, and now if user tries to access main.php without logging in, it will redirect him to the main page, so the code works!
n.b. The project is not mine, it belongs to the company I work in.
And I don't know which code is checking the session, all what I know is, if the user click on a player from the field after the session timeout, the "Please Login" message will be shown in the frame.
I'm guessing the redirect is essentially the same as using a header() function. It isn't possible to specify a target using a php redirect as it is server-side - specifying the target is client-side.
You would need to print something like this to the screen:
<script type="text/javascript">window.open('index.php','_parent');</script>
And that will redirect the user to the index.
Using frames for such purpose is... well... so 80ish...
Anyway, the frames are probably named in such a scenario. This means you can address them, but also that you have to address them. Just loading an url inside the "current" frame does exactly that, which is why your approach won't work.
If you really have to go with that frame based approach, then you will have to use javascript to address all known frames and redirect them.
Maybe you can use some javascript inside of your frame like so :
<script type="text/javascript">
window.top.location = 'YourPage.html';
</script>
Hope this helps
The issue was that the session expires while I'm on main.php. Therefore, any subsequent Ajax requested will fail since all requests requires session to be active.
the problem was that the Ajax request being sent from the IFrame (the IFrame is inside main.php and points to list.php thru Ajax calls) is failing due to session expiry.
So I've fixed this issue by adding another two session checks, one on main.php, list.php using PHP (check for session, if it's there, redirect). And in the main container, main.php, I check for the session via JS, interval Ajax requests to check the session, if session has ended, then use redirect using JS.
PHP:
$user_id = NSession::get('user_id');
if (isset($_POST["checklogin"]))//check loging
{
die(isset($user_id) ? "true" : "false");
}
if (!isset($user_id) || $user_id == "")
{
NSession::removeall();
General::Redirect('login.php');
}
JavaScript:
jQuery(document).ready(function($) {
$(window).focus(function() {
checkSession();
});
});
function checkSession()
{
$.ajax({
type: "POST",
data: {"checklogin": "cl"},
url: "list_players.php",
success: function(result) {
if (result === "false")
{
if (FIELD.showMessage === false)
{
FIELD.showMessage = true;
alert("Your session has been closed\nYou will be redirected to login page now. ");
window.location.href = ("login.php");//incase user clicks OK
}
}
}
});
}

Jquery/PHP - Prevent user from browsing to locked content

I have this simple login script:
$.ajax({
type: 'POST',
url: 'authorize.php',
data: { username: user, password: pass },
dataType: 'json',
success: function(data) {
if (data.status == "loggedIn") {
//Logged in
} else {
//Not logged in
}
}
});
Where //Logged in is, how should I call the page that required the login? I could simply $.load the page, but then what was the point of verifying a login when the user could just browse to this file in the first place?
I'd suggest using PHP Sessions across all of these pages. Make a check on the page you're going to $.load that the user is actually logged in and set the user as logged in on the authorize.php page if successful.
This way, if a user looks at the page source and see's what you're loading, but when they try and access that page it won't do anything because you're checking to see if they've been logged in already.
It's a matter of presentation, you can just load a div on another file, you don't need to load the whole thing.
I use ajax to login and $.load to "bring" a div I have in a template file. It's just because it makes it easier when you need to change the design.
Remember that splitting the work into individual "pieces" makes it easier for you to change things. Imagine you have the same login box on 20 individual templates. If you change one, you have to change 19 more.
You can't prevent a user from doing anything with javascript (jquery), since it is client-side and easily disabled/changed etc.
What you can do is simply $.load the page like you say, but also have a check against the session on the loaded page that checks for an actual login before sending the content. You'd need to set some variable in the session as part of authorize.php to indicate a successful login.
To prevent data from being accessed, you should look into using .htaccess and Apache's mod_rewrite. Whenever a user requests a piece of possibly sensitive data, you'll invisibly call a PHP page which will then serve up either the requested data or a 403 Forbidden.
Example:
.htaccess
RewriteEngine On
RewriteRule ^user-content/(.+) display_content.php?file=$1
Then, any files that would be accessed in user-content will be rerouted through display_content.php. You can also use this .htaccess file to help prevent hotlinking by refusing to display the resource if there's a referrer.
display_content.php
<?php
if (isLoggedIn($_COOKIE["username"], $_COOKIE["password"]) && isset($_GET["file"])) {
if (mimeTypeOk($_GET["file"]) { // Implementation not shown
readfile($_GET["file"]);
exit();
}
}
header("403 Forbidden");
?>
In order to do this the most secure way, you are going to have to use both jQuery as a client-side way and PHP as a server-side way of checking if the user is logged in. You don't need to load the entire page with jQuery, just use the following code to load only a div portion:
$("#load_dom").click(function(){
$("#result")
.html(ajax_load)
.load(loadUrl + " #picture");
});
Then, as a security measure, use PHP to restrict access to the page, by checking $_SESSION vars like this:
if (!isset($_SESSION['userid'])) {
// user is logged in
} else {
// user is not logged in
die("You are not logged in.");
}

SimpleModal PHP login form : how to redirect on success/failure

Hope you can help. A bit of a jQuery/AJAX newb here.
I have a basic SimpleModal login form that may be called from the homepage of my site.
login.js calls the login.php script that checks my database for a user's credentials.
If the login is successful I set a few session variables and I usually use the header command to send the user to their personal page (or the error page on login failure).
eg. header("Location:restricted/index.php");
I can't get the modal login form to close and the parent homepage to redirect to the member page. I'm usually left with the blank modal square saying "Thank You"
If i try to close the modal form with
success: function (data) {
$('#login-container .login-loading').fadeOut(200, function () {
$('#login-container .login-title').html('Thank you!');
msg.html(data).fadeIn(200);
$.modal.close(); //have inserted this line
});
},
the modal closes but I am left on the homepage. (The user is logged in at this stage but the redirect has not happened).
I've been kicking this around for a day or 2. I had a look at the wordpress login plugin but I am none the wiser. Any ideas?
Actually the redirect probably did happen, it just happened inside the AJAX request. When you do a redirect, the XmlHttpRequest that the ajax functions use transparently follows it, so then page that came back to the client is the restricted/index.php. what I tend to do is add a header on that page, something like this:
header("Redirect:restricted/index.php");
Then look for the header, something like this using $.ajaxSetup():
$.ajaxSetup({
complete: function (xhr) {
var redirect = xhr.getResponseHeader('Redirect');
if(redirect) window.location.href = redirect;
}
});
This way (unless you override complete, it leaves this option open) when a request comes back that made it to the restricted/index.php (remember the XmlHttpRequest actually went there) it'll get a header to let the client know it needs to redirect.

Categories