Is it possible to set PHP session variables using Javascript?
9 Answers
In JavaScript:
jQuery('#div_session_write').load('session_write.php?session_name=new_value');
In session_write.php file:
<?
session_start();
if (isset($_GET['session_name'])) {$_SESSION['session_name'] = $_GET['session_name'];}
?>
In HTML:
<div id='div_session_write'> </div>

- 605
- 1
- 8
- 28

- 342
- 3
- 2
-
33This may be a security risk if people use the session variables expecting that they can only be set server side. – Sam Stoelinga Apr 30 '14 at 04:06
The session is stored server-side so you cannot add values to it from JavaScript. All that you get client-side is the session cookie which contains an id. One possibility would be to send an AJAX request to a server-side script which would set the session variable. Example with jQuery's .post()
method:
$.post('/setsessionvariable.php', { name: 'value' });
You should, of course, be cautious about exposing such script.

- 605
- 1
- 8
- 28

- 1,023,142
- 271
- 3,287
- 2,928
If you want to allow client-side manipulation of persistent data, then it's best to just use cookies. That's what cookies were designed for.

- 7,923
- 2
- 33
- 44
-
but they come up with limitations @lese majeste. so i am looking to take my javascript array from one page to another page – saikiran Aug 05 '14 at 15:56
or by pure js, see also on StackOverflow : JavaScript post request like a form submit
BUT WHY try to set $_session with js? any JS variable can be modified by a player with some 3rd party tools (firebug), thus any player can mod the $_session[]! And PHP cant give js any secret codes (or even [rolling] encrypted) to return, it is all visible. Jquery or AJAX can't help, it's all js in the end.
This happens in online game design a lot. (Maybe a bit of Game Theory? forgive me, I have a masters and love to put theory to use :) ) Like in crimegameonline.com, I initialize a minigame puzzle with PHP, saving the initial board in $_SESSION['foo']. Then, I use php to [make html that] shows the initial puzzle start. Then, js takes over, watching buttons and modding element xy's as players make moves. I DONT want to play client-server (like WOW) and ask the server 'hey, my player want's to move to xy, what should I do?'. It's a lot of bandwidth, I don't want the server that involved.
And I can just send POSTs each time the player makes an error (or dies). The player can block outgoing POSTs (and alter local JS vars to make it forget the out count) or simply modify outgoing POST data. YES, people will do this, especially if real money is involved.
If the game is small, you could send post updates EACH move (button click), 1-way, with post vars of the last TWO moves. Then, the server sanity checks last and cats new in a $_SESSION['allMoves']. If the game is massive, you could just send a 'halfway' update of all preceeding moves, and see if it matches in the final update's list.
Then, after a js thinks we have a win, add or mod a button to change pages:
document.getElementById('but1').onclick=Function("leave()");
...
function leave() {
var line='crimegameonline-p9b.php';
top.location.href=line;
}
Then the new page's PHP looks at $_SESSION['init'] and plays thru each of the $_SESSION['allMoves'] to see if it is really a winner. The server (PHP) must decide if it is really a winner, not the client (js).
-
ps: one would likely use AJAX to (get or post) submit individual moves, without going to the action page, to an action .php page that cats them into a session var (no text / header info). – dako Oct 08 '12 at 23:21
-
URL arguments are not "all visible". If your goal is to eliminate arguments from URLs so they look cleaner, and security is not an issue, then cookies or other browser storage is a good way to propagate data throughout the JavaScript of a website. If security is an issue, then, yes, solutions are very difficult because client-side security is not supported by the Web infrastructure, only server-side. – David Spector Jun 25 '23 at 10:36
You can't directly manipulate a session value from Javascript - they only exist on the server.
You could let your Javascript get and set values in the session by using AJAX calls though.
See also

- 1
- 1

- 295,876
- 54
- 310
- 348
be careful when doing this, as it is a security risk. attackers could just repeatedly inject data into session variables, which is data stored on the server. this opens you to someone overloading your server with junk session data.
here's an example of code that you wouldn't want to do..
<input type="hidden" value="..." name="putIntoSession">
..
<?php
$_SESSION["somekey"] = $_POST["putIntoSession"]
?>
Now an attacker can just change the value of putIntoSession and submit the form a billion times. Boom!
If you take the approach of creating an AJAX service to do this, you'll want to make sure you enforce security to make sure repeated requests can't be made, that you're truncating the received value, and doing some basic data validation.

- 11
- 2
One simple way to set session variable is by sending request to another PHP file. Here no need to use Jquery or any other library.
Consider I have index.php file where I am creating SESSION
variable (say $_SESSION['v']=0
) if SESSION
is not created otherwise I will load other file.
Code is like this:
session_start();
if(!isset($_SESSION['v']))
{
$_SESSION['v']=0;
}
else
{
header("Location:connect.php");
}
Now in count.html I want to set this session variable to 1.
Content in count.html
function doneHandler(result) {
window.location="setSession.php";
}
In count.html javascript part, send a request to another PHP file (say setSession.php
) where i can have access to session variable.
So in setSession.php will write
session_start();
$_SESSION['v']=1;
header('Location:index.php');

- 665
- 6
- 22
-
I don't understand what problem this solves. It just seems to redirect to the main page once only. – David Spector Jun 25 '23 at 14:38
Not possible. Because JavaScript is client-side and session is server-side. To do anything related to a PHP session, you have to go to the server.

- 605
- 1
- 8
- 28

- 11,393
- 7
- 25
- 36
I solved this question using Ajax. What I do is make an ajax call to a PHP page where the value that passes will be saved in session.
The example that I am going to show you, what I do is that when you change the value of the number of items to show in a datatable, that value is saved in session.
$('#table-campus').on( 'length.dt', function ( e, settings, len ) {
$.ajax ({
data: {"numElems": len},
url: '../../Utiles/GuardarNumElems.php',
type: 'post'
});
});
And the GuardarNumElems.php is as following:
<?php
session_start();
if(isset ($_POST['numElems'] )){
$numElems = $_POST['numElems'];
$_SESSION['elems_table'] = $numElems;
}else{
$_SESSION['elems_table'] = 25;
}
?>

- 568
- 13
- 32