Set Session variable using javascript in PHP












35















Is it possible to set PHP session variables using Javascript?










share|improve this question





























    35















    Is it possible to set PHP session variables using Javascript?










    share|improve this question



























      35












      35








      35


      3






      Is it possible to set PHP session variables using Javascript?










      share|improve this question
















      Is it possible to set PHP session variables using Javascript?







      php javascript session






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Oct 23 '12 at 14:12









      rolve

      7,75044165




      7,75044165










      asked Aug 28 '10 at 9:59









      Sanjay KhatriSanjay Khatri

      2,02962540




      2,02962540
























          9 Answers
          9






          active

          oldest

          votes


















          27














          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>





          share|improve this answer





















          • 26





            This 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 4:06



















          18














          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.






          share|improve this answer

































            7














            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.






            share|improve this answer
























            • 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 5 '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).






            share|improve this answer


























            • 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 8 '12 at 23:21



















            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




            • Javascript and session variables

            • jQuery click event to change php session variable






            share|improve this answer

































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





              share|improve this answer

































                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.






                share|improve this answer

































                  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.






                  share|improve this answer

































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





                    share|improve this answer























                      Your Answer






                      StackExchange.ifUsing("editor", function () {
                      StackExchange.using("externalEditor", function () {
                      StackExchange.using("snippets", function () {
                      StackExchange.snippets.init();
                      });
                      });
                      }, "code-snippets");

                      StackExchange.ready(function() {
                      var channelOptions = {
                      tags: "".split(" "),
                      id: "1"
                      };
                      initTagRenderer("".split(" "), "".split(" "), channelOptions);

                      StackExchange.using("externalEditor", function() {
                      // Have to fire editor after snippets, if snippets enabled
                      if (StackExchange.settings.snippets.snippetsEnabled) {
                      StackExchange.using("snippets", function() {
                      createEditor();
                      });
                      }
                      else {
                      createEditor();
                      }
                      });

                      function createEditor() {
                      StackExchange.prepareEditor({
                      heartbeatType: 'answer',
                      autoActivateHeartbeat: false,
                      convertImagesToLinks: true,
                      noModals: true,
                      showLowRepImageUploadWarning: true,
                      reputationToPostImages: 10,
                      bindNavPrevention: true,
                      postfix: "",
                      imageUploader: {
                      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                      allowUrls: true
                      },
                      onDemand: true,
                      discardSelector: ".discard-answer"
                      ,immediatelyShowMarkdownHelp:true
                      });


                      }
                      });














                      draft saved

                      draft discarded


















                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3590293%2fset-session-variable-using-javascript-in-php%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown

























                      9 Answers
                      9






                      active

                      oldest

                      votes








                      9 Answers
                      9






                      active

                      oldest

                      votes









                      active

                      oldest

                      votes






                      active

                      oldest

                      votes









                      27














                      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>





                      share|improve this answer





















                      • 26





                        This 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 4:06
















                      27














                      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>





                      share|improve this answer





















                      • 26





                        This 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 4:06














                      27












                      27








                      27







                      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>





                      share|improve this answer















                      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>






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Apr 25 '16 at 20:02









                      WolfieeifloW

                      329217




                      329217










                      answered Oct 23 '12 at 13:52









                      BGabeszBGabesz

                      29432




                      29432








                      • 26





                        This 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 4:06














                      • 26





                        This 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 4:06








                      26




                      26





                      This 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 4:06





                      This 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 4:06













                      18














                      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.






                      share|improve this answer






























                        18














                        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.






                        share|improve this answer




























                          18












                          18








                          18







                          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.






                          share|improve this answer















                          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.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Apr 25 '16 at 20:12









                          WolfieeifloW

                          329217




                          329217










                          answered Aug 28 '10 at 10:02









                          Darin DimitrovDarin Dimitrov

                          844k22230142746




                          844k22230142746























                              7














                              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.






                              share|improve this answer
























                              • 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 5 '14 at 15:56
















                              7














                              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.






                              share|improve this answer
























                              • 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 5 '14 at 15:56














                              7












                              7








                              7







                              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.






                              share|improve this answer













                              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.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Aug 28 '10 at 10:05









                              Lèse majestéLèse majesté

                              6,53022641




                              6,53022641













                              • 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 5 '14 at 15:56



















                              • 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 5 '14 at 15:56

















                              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 5 '14 at 15:56





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






                              share|improve this answer


























                              • 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 8 '12 at 23:21
















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






                              share|improve this answer


























                              • 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 8 '12 at 23:21














                              3












                              3








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






                              share|improve this answer















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







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited May 23 '17 at 11:54









                              Community

                              11




                              11










                              answered Oct 8 '12 at 18:30









                              dakodako

                              312




                              312













                              • 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 8 '12 at 23:21



















                              • 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 8 '12 at 23:21

















                              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 8 '12 at 23:21





                              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 8 '12 at 23:21











                              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




                              • Javascript and session variables

                              • jQuery click event to change php session variable






                              share|improve this answer






























                                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




                                • Javascript and session variables

                                • jQuery click event to change php session variable






                                share|improve this answer




























                                  1












                                  1








                                  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




                                  • Javascript and session variables

                                  • jQuery click event to change php session variable






                                  share|improve this answer















                                  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




                                  • Javascript and session variables

                                  • jQuery click event to change php session variable







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited May 23 '17 at 12:09









                                  Community

                                  11




                                  11










                                  answered Aug 28 '10 at 10:02









                                  Paul DixonPaul Dixon

                                  243k41281318




                                  243k41281318























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





                                      share|improve this answer






























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





                                        share|improve this answer




























                                          1












                                          1








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





                                          share|improve this answer















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






                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Nov 22 '18 at 5:55

























                                          answered Nov 12 '14 at 15:58









                                          ShashidharaShashidhara

                                          463311




                                          463311























                                              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.






                                              share|improve this answer






























                                                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.






                                                share|improve this answer




























                                                  0












                                                  0








                                                  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.






                                                  share|improve this answer















                                                  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.







                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Apr 25 '16 at 18:55









                                                  WolfieeifloW

                                                  329217




                                                  329217










                                                  answered Jan 4 '11 at 9:50









                                                  Ms_Lucky13Ms_Lucky13

                                                  4,80741528




                                                  4,80741528























                                                      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.






                                                      share|improve this answer






























                                                        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.






                                                        share|improve this answer




























                                                          0












                                                          0








                                                          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.






                                                          share|improve this answer















                                                          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.







                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited May 25 '16 at 3:08

























                                                          answered May 25 '16 at 3:02









                                                          Payam AzadiPayam Azadi

                                                          11




                                                          11























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





                                                              share|improve this answer




























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





                                                                share|improve this answer


























                                                                  0












                                                                  0








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





                                                                  share|improve this answer













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






                                                                  share|improve this answer












                                                                  share|improve this answer



                                                                  share|improve this answer










                                                                  answered Jan 16 at 15:36









                                                                  JoacerJoacer

                                                                  386923




                                                                  386923






























                                                                      draft saved

                                                                      draft discarded




















































                                                                      Thanks for contributing an answer to Stack Overflow!


                                                                      • Please be sure to answer the question. Provide details and share your research!

                                                                      But avoid



                                                                      • Asking for help, clarification, or responding to other answers.

                                                                      • Making statements based on opinion; back them up with references or personal experience.


                                                                      To learn more, see our tips on writing great answers.




                                                                      draft saved


                                                                      draft discarded














                                                                      StackExchange.ready(
                                                                      function () {
                                                                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3590293%2fset-session-variable-using-javascript-in-php%23new-answer', 'question_page');
                                                                      }
                                                                      );

                                                                      Post as a guest















                                                                      Required, but never shown





















































                                                                      Required, but never shown














                                                                      Required, but never shown












                                                                      Required, but never shown







                                                                      Required, but never shown

































                                                                      Required, but never shown














                                                                      Required, but never shown












                                                                      Required, but never shown







                                                                      Required, but never shown







                                                                      Popular posts from this blog

                                                                      MongoDB - Not Authorized To Execute Command

                                                                      How to fix TextFormField cause rebuild widget in Flutter

                                                                      Npm cannot find a required file even through it is in the searched directory