41

Is it possible to set PHP session variables using Javascript?

rolve
  • 9,021
  • 4
  • 50
  • 70
Sanjay Khatri
  • 3,827
  • 6
  • 32
  • 42

9 Answers9

31

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>
WolfieeifloW
  • 537
  • 1
  • 3
  • 24
BGabesz
  • 334
  • 3
  • 2
20

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.

WolfieeifloW
  • 537
  • 1
  • 3
  • 24
Darin Dimitrov
  • 960,118
  • 257
  • 3,196
  • 2,876
8

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.

Lèse majesté
  • 7,526
  • 2
  • 30
  • 42
  • 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
3

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

Community
  • 1
  • 1
dako
  • 31
  • 2
  • 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
1

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');
Shashidhara
  • 607
  • 6
  • 18
1

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

Community
  • 1
  • 1
Paul Dixon
  • 277,937
  • 48
  • 303
  • 335
0

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.

0

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.

WolfieeifloW
  • 537
  • 1
  • 3
  • 24
Lucky13
  • 10,849
  • 6
  • 21
  • 34
0

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;
    } 
?>
Joacer
  • 502
  • 9
  • 30