Set Session variable using javascript in PHP

后端 未结 9 916
刺人心
刺人心 2020-11-27 21:23

Is it possible to set PHP session variables using Javascript?

相关标签:
9条回答
  • 2020-11-27 22:07

    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 讨论(0)
  • 2020-11-27 22:10

    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.

    0 讨论(0)
  • 2020-11-27 22:13

    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;
        } 
    ?>
    
    0 讨论(0)
提交回复
热议问题