[php] Set Session variable using javascript in PHP

Is it possible to set PHP session variables using Javascript?

This question is related to php javascript session

The answer is


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.


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.


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

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


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.


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


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.


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

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to session

What is the best way to manage a user's session in React? Spring Boot Java Config Set Session Timeout PHP Unset Session Variable How to kill all active and inactive oracle sessions for user Difference between request.getSession() and request.getSession(true) PHP - Session destroy after closing browser Get Current Session Value in JavaScript? Invalidating JSON Web Tokens How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session How can I get session id in php and show it?