Jump to content

PHP Session Variables

elcou96
Go to solution Solved by Mr_KoKa,

There are few things.

You reload page just after calling ajax. Ajax is async, so it puts a call on js event queue, but reload is immediate, so the possibility is that you reload page before ajax request manages to fire, this is why it may work on localhost as there is not much delay, and it is not working on remote host.

 

to fix this reload your page inside complete callback of ajax method. It depends of what version of jQuery do you use.

 

Other thing is, why do you use ajax when you reload page anyway? You use ajax to get data without page reloading.

I am having an issue with setting php session variables.

Here is what I'm trying to do:

I'm creating a website that pulls data from a database. In the database, there are movie theater schedules of three different cities. (not that relevant, but might be useful to see the reason why I need this)

So I want to use Session variables and a way to select one of those movie theaters.

My index page is as follows:

[code]
<?php
	session_start();
	if (!isset($_SESSION['varToSet'])){
    
		include('template/selectVarVal.php'); // Var Setting
        
	}
	else {
	
		include('template/header.php'); // Page Header
		
		include('views/'.$view['name'].'.php'); // View Type
		
		include('template/footer.php'); // Page Footer
		
	}
?>
[/code]

So if the session variable varToSet is not set, you will get a page displaying the three options. These are three html buttons:

[code]
<button id="btnVarToSetVal1" class="btnstyle center-block">Val1</button>
[/code]

The buttons use javascript to send an ajax request to set the session variable:

[code]
		$('#btnVarToSetVal1').on('click', function(e){
		    var name = 1;
		    $.ajax({
		        type: 'POST',
		        url: 'config/SetVar.php',
		        data: {
		            VarToSet: name
		        }
		    }); 
			location.reload()
		});
[/code]

with the php in SetVar.php:

[code]
<?php
	session_start();
	if($_POST['VarToSet'] != 0){
		$VarToSet = $_POST['VarToSet'];
		session_registrer($VarToSet);
		$_SESSION['VarToSet'] = $_POST['VarToSet'];
		//header("Location: index.php");
		
	}
	else{
		unset($_SESSION['VarToSet']);
		//header("Location: index.php");
	}
?>
[/code]

Thus, the javascript should start the php to set the session variable and reload the index page, which then has the VarToSet-variable set and should display the correct page instead of the SelectValVar-page.

This works on my localhost (xampp apache server), but only on chrome and not on firefox and edge. It doesn't work on the Host I am deploying the website to at all, not even on chrome.

When I click one of the buttons, the page reloads, but keeps displaying the SelectValVar-page.

As far as I can tell the session-id stays the same, but the session variable doesn't get set, or doesn't stick.

Yesterday I managed to get the page to load the correct page, but when switching pages (using the navigation) it lost the session-variables again and it displayed the SelectValVar-page anew.

The Host is using an older version of php (5.3.29) which also causes some other issues but to my knowledge that shouldn't affect the setting of session variables.

 

Am I doing something wrong? What can I do to get the damned thing to work??

Link to comment
Share on other sites

Link to post
Share on other sites

If it works for one browser but not the other, it's probably a JS rendering issue. Do you absolutely need to use Javascript? Would a "form" work posting to your SetVar.php not work for what you want? 

 

Another note, could you be calling the same file more than once in your code? Might have nothing to do with it, but give it a chance: Change your php "includes" into "require_once". Also any variables inside the php files being included should be predefined as "global" in order to be usable in the rest of your page.

 
~ Specs bellow ~
 
 
Windows 10 Pro 64-bit [UEFI]
CPU: Intel i7-5820k Haswell-E @ 4.5-4.7Ghz (1.366-1.431V) | CPU COOLER: Corsair H110 280mm AIO w/ 2x Noctua NF-A14 IPPC-2000 IP67 | RAM: G.Skill Ripjaws 4 32Gb (8x4Gb) DDR4 @ 2666mhz CL15 | MOBO: MSI X99S Gaming 7 ATX | GPU: MSI GTX 1080 Gaming (flashed "X") @ 2138-2151Mhz (locked 1.093V) | PSU: Corsair HX850i 850W 80+ Platinum | SSD's: Samsung Pro 950 256Gb & Samsung Evo 850 500Gb | HDD: WD Black Series 6Tb + 3Tb | AUDIO: Realtek ALC1150 HD Audio | CASE: NZXT Phantom 530 | MONITOR: LG 34UC79G 34" 2560x1080p @144hz & BenQ XL2411Z 24" 1080p @144hz | SPEAKERS: Logitech Z-5450 Digital 5.1 Speaker System | HEADSET: Sennheiser GSP 350 | KEYBOARD: Corsair Strafe MX Cherry Red | MOUSE: Razer Deathadder Chroma | UPS: PowerWalker VI 2000 LCD
 
Mac Pro 2,1 (flashed) OS X 10.11.6 El Capitan 64-bit (NAS, Plex, HTTP Server, Game Servers) [R.I.P]
CPUs: 2x Intel Xeon X5365 @ 3.3Ghz (FSB OC) | RAM: OWC 16Gb (8x2Gb) ECC-FB DDR2 @ 1333mhz | GPU: AMD HD5870 (flashed) | HDDs: WD Black Series 3Tb, 2x WD Black Series 1Tb, WD Blue 2Tb | UPS: Fortron EP1000
 
Link to comment
Share on other sites

Link to post
Share on other sites

There are few things.

You reload page just after calling ajax. Ajax is async, so it puts a call on js event queue, but reload is immediate, so the possibility is that you reload page before ajax request manages to fire, this is why it may work on localhost as there is not much delay, and it is not working on remote host.

 

to fix this reload your page inside complete callback of ajax method. It depends of what version of jQuery do you use.

 

Other thing is, why do you use ajax when you reload page anyway? You use ajax to get data without page reloading.

Link to comment
Share on other sites

Link to post
Share on other sites

Ok, now the session variable gets set without ajax, using forms and $_Post, it loads the page correct, but I lose the value of the variable when I reload the page, the session-id is still kept.

Link to comment
Share on other sites

Link to post
Share on other sites

Can you post code?

 

Only thing I noticed is 

$VarToSet = $_POST['VarToSet'];
session_registrer($VarToSet);

Which is used wrong, session_register takes name of global variable, not variable itself, and it is deprecated since PHP 4.1

 

This should be enough, you can try to debug this and var_dump $_SESSION and $_POST after this line.

$_SESSION['VarToSet'] = $_POST['VarToSet'];

 

Link to comment
Share on other sites

Link to post
Share on other sites

Yeah I'm not using that anymore, and the only reason I did that, was because I hoped that might help.

 

right now: 

index.php:

[code]
<?php
	ini_set("session.save_path", "tmp");
	session_start();
	if(isset($_POST['VarToSet'])){
		if($_POST['VarToSet'] == "val1"){
			$_SESSION['VarToSet']=1;
		}
		if($_POST['VarToSet'] == "val2"){
			$_SESSION['VarToSet']=2;
		}
		if($_POST['VarToSet'] == "val3"){
			$_SESSION['VarToSet']=3;
		}
		session_write_close();
		header('Location: index.php');		
	}
	if (!isset($_SESSION['VarToSet'])){
		
		include('template/SelectValVar.php'); // Var Setting
	}
	else {
	
		include('template/header.php'); // Page Header
		
		include('views/'.$view['name'].'.php'); // View Type
		
		include('template/footer.php'); // Page Footer
		
	}
	
	
?>
[/code]

selectVarVal.php:

[code]
	<form method="POST" action="index.php">
		<div class="col-md-2">
			<input type="submit" class="btnstyle center-block" id="val1" name="VarToSet" value="val1" />
		</div>
		<div class="col-md-2">
			<input type="submit" class="btnstyle center-block" id="val2" name="VarToSet" value="val2" />
		</div>
		<div class="col-md-2">
			<input type="submit" class="btnstyle center-block" id="val3" name="VarToSet" value="val3" />
		</div> 
	</form>
[/code]
Link to comment
Share on other sites

Link to post
Share on other sites

also apparently something is changing $_session['VarToSet'] to corresponding date pulled from the db, that might be the issue, but I don't remember/can't find where I did that... o.O

Link to comment
Share on other sites

Link to post
Share on other sites

Good to hear, do you prepare queries and bind parameters to prevent sql injections?

Link to comment
Share on other sites

Link to post
Share on other sites

yeah, I escaped the strings on the two places that were vulnerable to sql injections (email and password for admin login). For a regular user there is never a place where they have to enter text that's used in a query (no forms and such), so I should be all right I think :) 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×