Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

local storage - Loading JS LocalStorage into PHP Variable

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.

Here is my code.

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

<?php
$user_email = "<script>document.write(localStorage.getItem('email'));</script>";
$password = "<script>document.write(localStorage.getItem('password'));</script>";

define('XOAUTH_USERNAME', $user_email);
define('XOAUTH_PASSWORD', $password);
?>

<html>
<head></head>
<body></body>
</html>

I know that I am setting the localstorage right because I'm checking in chrome and both key and value are correct. I'm just have trouble passing the value of the keys into the define() of my php.

Thanks for the help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...