Loading JS LocalStorage into PHP Variable

后端 未结 3 1354
轻奢々
轻奢々 2020-12-30 10:11

In the header of my doc I am defining a email and password. I would like to user local storage. However I am having trouble loading items from localstorage into my php vars.

相关标签:
3条回答
  • 2020-12-30 11:05

    If you just need to save an email and password (small data), then you could use cookies for this, which you can access via PHP and via JavaScript.

    How to set a cookie in PHP:

    setcookie("TestCookie", $value, time()+3600, "/", "example.com");
    

    How to delete a cookie:

    setcookie("TestCookie", $value, time()-3600, "/", "example.com");
    

    How to get a cookie in PHP:

    $_COOKIE["TestCookie"]
    

    The last parameter in this example:

    setcookie("TestCookie", $value, time()+3600, "/", "example.com", 1);
    

    indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. When set to TRUE, the cookie will only be set if a secure connection exists. On the server-side, it's on the programmer to send this kind of cookie only on secure connection (e.g. with respect to $_SERVER["HTTPS"]).

    Source: https://secure.php.net/manual/en/function.setcookie.php

    0 讨论(0)
  • 2020-12-30 11:05

    This is errate, do so

    <script>
       localStorage.setItem('email', "<?php echo $_SESSION['email'];?>");
       localStorage.setItem('password', "<?php echo $_SESSION['password'];?>");
    </script>
    
    0 讨论(0)
  • 2020-12-30 11:06

    You cannot access localstorage via PHP. You need to write some javascript that sends the localstorage data back to the script.

    If you are using jQuery, do something like the following.

    set_page.php

    <script>
    localStorage.setItem('email', '<?php echo $_SESSION['email'];?>');  
    localStorage.setItem('password', '<?php echo $_SESSION['password'];?>');
    </script>
    

    login_page.php

    <script>
    var email = localStorage.getItem('email'), password = localStorage.getItem('password');
    $.POST('login_response.php', {'email':email,'password':password}, function(data){
      alert('Login Successful.  Redirect to a different page or something here.');
    }
    </script>
    

    login_response.php

    <?
    $email = $_POST['email'];
    $password = $_POST['password'];
    //Handle your login here.  Set session data, etc.  Be sure to sanitize your inputs.
    ?>
    

    Remember, people can edit what is in their local storage, so never ever trust user input. A crafty intruder could simply start posting data to your login_response.php page as well.

    0 讨论(0)
提交回复
热议问题