jQuery AJAX and PHP session issue - php

Really hope this makes sense and someone can point me in right direction. On a registration page (parent page), when you enter a license code a jQuery ajax success function loads content from another page with an appended url to include a session id:
success: function(data) {
if (data=="RegisterError") {
$("#error").show();
$("#processing").hide();
} else {
$("#contain").load("download-software.php?sessionid=xXXX #req");
}
}
The page "download-software" has the following PHP referrer check to make sure the content is being requested from the registration page via the session ID and redirects you if it's not:
<?php
$code = $_GET['sessionid'];
if(strcmp( $code , 'xXXX' ) != 0) {
header("Location: http://www.someotherpage.com");
}
?>
That works fine. Now what I need to do is in the "download-software #req" content that is loaded into the parent page, have a link that when clicked replaces the "download-software #req" content which has been loaded inside the parent page with content from another page and do the same type of session id check.
I cannot get it to work. I place the following code on the "download-software #req" content for the
<a id="beta">beta notes
$("#beta").click(function() {
$("#req").load("NT7-SP1-Download.php #betaNotes");
});`
I've also tried using the .live function. How do I start a new session and make this work?
*answer**
I used the live function on the parent page and it works fine. Making it too hard i guess.

I would refrain from using GET query string parameters and use the included PHP session functions.
use:
<?php
// initialize the session
session_start();
// assignment call
$_SESSION['key'] = 'value';
?>
You can retrieve data from the session on the same server in subsequent page requests.
When you are done with the session, use: session_destroy()

Related

Index page refresh when logged-in

I have an index.php page, which behaves as follows :
if a session var exists and is set, it displays a menu + some info
about the user (userID, IP adress, link to disconnect)
if the session var is not set, it displays a login form
So if you go there for the first time, you'll see the login form.
When the user provides his login+password, there is an AJAX call to login_check.php. The main purpose of this page is to generate a session variable (if the user info meets several requirements), but it also sends error messages back to the bottom of the form (under the form of JSON var) in case of authentification failure.
Here is its core :
login_check.php
if (authentification($login, $password)) {
//creates the session variable
$_SESSION['auth'] = $login;
//? here I'd like to refresh the index page
}
else {
//the error that will be displayed at the bottom of the form
$json_err .= "Incorrect login or password";
}
index.php looks like this :
if (isset($_SESSION['auth'])) {
//the menu is displayed, because the user is looged-in
}
else {
//the login form is displayed, because the user is not authentificated
}
So far, I have to manually refresh the index page so that it takes the session var into account. Is there a way to do it automatically ?
Solutions like "location.reload" are not really suitable, because of the error messages that might be displayed. I also tried to call again index.php from login_check.php using "include" or "header" but it didn't work.
Should I make a conditional refresh within my jQuery function, depending on what data was sent back by login_check.php ?
What would you advice ?
Thanks
I think you need to eun your checklogged.php for example once every 5 min and if user if not logged redirect to login page.
<script type="text/javascript">
$(function() {
getStatus();
});
function getStatus() {
$status = $('#islogged').load('login_check.php');
setTimeout("getStatus()",50000);
}
</script>

use session cookies per specific browsertab

I currently have a form that allows a user to edit entries. However, it doesn't seem to be possible to use 1 (specific) cookie per tab. Whenever a user edits an entry, the record in the last tab gets updated.
I've tried the following in my main script (eventfilters.php):
<?php
$cookie_name = $_SESSION['username'].md5(time());
session_name($cookie_name);
setcookie(session_name($cookie_name),session_id(),time()+"300");
if(!isset($_SESSION)){ session_start(); }
if (isset($_GET['edit'])){
// Pass cookiename in url variable $cookie, so it gets caught by $_GET['cookie']
echo '<form action="eventfilters.php?save&cookie='.session_name().'" method="post">';
} else if (isset($_GET['save'])){
if(isset($_GET['cookie'])){
error_log("SAVE ".$_GET['cookie']); // Displays cookie url variable set by form action.
error_log("LOW ".$_SESSION['level_low']);
// Displays correct session value received from ajax
}
}
?>
`
The ajaxcode (also in eventfilters.php) contains this (called few times when page is already loaded):
$.post("include/severitygroups.php",{'cookie_name': "<?php echo $cookie_name; ?>", 'serialized_sev_groups': serialized_sev_groups}, function(data){});
This seems to pass the right cookiename to the other script, which successfully seems to return $_SESSION['level_low'] (as it appears in the error_log).
<?php
include('pdodb.php');
if(!isset($_SESSION)){ session_start(); }
$cookie_name = $_POST['cookie_name'];
error_log("SCRIPT ".$cookie_name);
error_log("COOKIEDATA ".$_COOKIE["$cookie_name"]);
// populating $_SESSION['level_low']
?>
It seems that the $_GET['save'] is populating the wrong sessions (initialised by the last loaded instance of eventfilters.php), even when the $_GET['save'] logs the right $_SESSION['level_low'] to the errorlog.
What is going wrong?
You can't do it. The best way to do it, is with Ajax, so, you will pass an "ID" to each tab (or page) like:
editPost.php?id=someID
And, each time you press save, you should send your content with your id param to save it.

session not created in php function

i'm trying to make a login page in php using ajax and php functions..
i'm trying to create a session inside the function. and i fail to make it work.
this is basicly what i'm trying to do
the ajax code is
$.post("process.php?do=createSession",
function(data) {alert("Data Loaded: " + data);});
in process.php i got this script
include ( 'bod_function.php' );
$process_func = $_REQUEST['do'];
echo BODeal::$process_func();
and in the bod_function.php i got this running
class BODeal {
public static function createSession() {
session_start();
$_SESSION['test']='Success';
return 'yeah';
}
}
i got the alert box running and saying 'yeah' but $_SESSION['test'] is empty. no session has been created.
The session needs to be started in each new page you open. I think what you want to do is start the session from the page you are calling from and leave it empty. Then when you make your AJAX call you will need to start the session again, as you have, and then set:
$_SESSION['test']='Success';
When you have a session in PHP each page that is included in the session needs a call to session_start() before the global $_SESSION can be accessed.

PHP+AJAX (jQuery) - Reading session data on $.post() return

I am currently writing an "Edit Account" module. Using jQuery.post(); I can successfully update my database, and I can write to the session variables from the PHP script - however,
when trying to access the Session variable that I just wrote to, the data does not seem to have been updated.
I write to the session like this: $_SESSION['email'] = 'john#doe.com'; in my Ajax.php
My jQuery (minified) callback on success:
$.post(...,function(res)
{
if(res=='success')
{
// Alert the new E-Mail, read from the Session!
alert("<?php echo $_SESSION['email']; ?>");
}
}
However, the alert does not output john#doe.com, it outputs whatever the E-Mail was it was when the entire page was loaded. When I refresh the page, the session data has been properly updated.
I do have session_start(); on both index.php (my site) and in Ajax.php
If you need more info please do let me know. :)
First of all it should be
alert("<?php echo $_SESSION['email']; ?>");
and secondly $.post is dynamic but <?php echo $_SESSION['email']; ?> is static. It renders once, on load, not everytime you make an .post() so if
$_SESSION['email'] = 'blah'; by the time the page is loaded, the alert will always be alert("blah"); , until you reload the page.
If you want to alert the new session variable you have to make a new ajax request to a php file (ie. return_session.php?key=email ), that will return the new session variable
Thats because the alert string is generated when the page is loaded. And when you make an ajax request it still doesnt change, because its not refreshed.
On ajax success you should output the responseText and then it will work.

PHP Session ID the same but variables are lost

I have a login page that sets session variables upon successful login. The login page then redirects to an admin page. The admin page is able to read session variables just fine. But when I do a jQuery load() function that loads viewUsers.php in the content div the session variables are gone. The weird part is the session id is the same.
I used var_dump() on both the admin page and the viewUsers page. The admin pages shows all the proper variables from the login page but the viewUsers page which is called with a jQuery load() function var_dump of $_SESSION is blank. var_dump of $_COOKIE['PHPSESSID'] has the proper ID though, it doesn't make any sense to me.
This is how I set the session variables.
$_SESSION['userID'] = $userInfo['ID'];
$_SESSION['userType'] = $userInfo['userType'];
$_SESSION['programID'] = $userInfo['programID'];
This is the jQuery
$("#content").load("viewUsers.php");
All pages have session_start() at the very top. The session variables also didn't work when I tried window.open and window.location instead of a jQuery load() function.
Some how the session variables are getting lost even though I have the correct session id. If anyone could shed any light on this I would really appreciate it!
As of right now I'm populating hidden fields and using a post function instead of load to get around it. I understand this isn't the best way, but it's the only way I could figure out how to do it.
Edit:
Here is the top of the index which read the session variables fine.
<?php
session_start();
//require("session.php");
if(!isset($_SESSION['userID'])){
header("location: ../login/index.php");
}
?>
Here is the entire viewusers
<?php
session_start();
//foreach($_POST as $name => $value){
//$_SESSION[$name] = $value;
//}
//echo " session id " . $_COOKIE['PHPSESSID'];
var_dump($_COOKIE);
var_dump($_SESSION);
?>
<?php require("adminFunctions.php"); ?>
<h2>View Current Users</h2>
<?php require("userlinks.php"); ?>
<table id="userTable" class="tablesorter">
<?php getUsers($_SESSION['programID'], $_SESSION['userType']) ?>
</table>
<script type="text/javascript">
$('td[name="userID"]').hide();
//$("#userTable th").click(function(){
//color();
//colorTable();
//color();
//});
function colorTable(){
$("tr:odd").css("background-color", "#c0c0c0");
$("tr:even").css("background-color", "#ffffff");
}
function color(){
$("tr:odd").css("background-color", "#ffffff");
$("tr:even").css("background-color", "#ffffff");
}
$(document).ready(function(){
//colorTable();
$("#userTable").tablesorter({widgets: ['zebra']});
});
</script>
Another Edit:
Here is the javascript code to load viewusers
The only reason I'm using post is because I set the session variables as hidden fields in order to pass session variables. On viewusers I use a foreach loop to set the session variables. I understand this isn't secure.
function maintainUsers(){
$.post("viewUsers.php", $("#sessionform").serialize(),function(data){
//alert(data);
$("#content").load("viewUsers.php");
});
}
Might be a long shot but are you using any framework or cms? I know that wordpress would delete session variables (http://blog.ginchen.de/en/2008/08/15/session-variablen-in-wordpress/) can you show the javascript code you're using to load viewUsers? Are you programming on a local server?
If you got correct $_COOKIE['PHPSESSID'], then try to add session_id() assignment before session_start() like this:
<?php
/** Add this: **/
if (isset($_COOKIE['PHPSESSID']))
session_id($_COOKIE['PHPSESSID']);
/** Start session **/
session_start();
/** Rest of the script... **/
if(!isset($_SESSION['userID'])){
header("location: ../login/index.php");
}
?>
I use this all the time and have no problems with sessions in PHP.
You have some spaces before the php open tag. They send output to the browser, and thus, session doesn't get started.
I suspect that the session isn't being started. I've had similar problems in the past all to find out that the session was not started in the first place.
A question: did you try printing out the value in the session variable just to make sure it's there? :
Before calling the page
and after calling the page.
Normally, this sort of error occurs when you dont use session_start() to read the session data.
Try placing (Although, you said you have, I would suggest rechecking)
session_start();
At the beginning of your viewUsers.php
In case, the above is not the case, thenyour current page (the one from which you execute the .load() function) is resetting the session and tampering with the values. Unless you upload the code or find it out, there is no solution for this case.
I would suggest something simple.
Include this in EVERY file.
<?php
session_name("yourapplication_session");
session_start();
?>

Categories