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.

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!

4

4 回答 4

15

您不能通过 PHP 访问 localstorage。您需要编写一些将本地存储数据发送回脚本的 javascript。

如果您使用的是 jQuery,请执行以下操作。

set_page.php

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

登录页面.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.
?>

请记住,人们可以编辑本地存储中的内容,因此永远不要相信用户输入。狡猾的入侵者也可以简单地开始将数据发布到您的 login_response.php 页面。

于 2012-11-27T14:44:12.043 回答
3

如果您只需要保存电子邮件和密码(小数据),那么您可以为此使用 cookie,您可以通过 PHP 和 JavaScript 访问它们。

如何在 PHP 中设置 cookie:

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

如何删除cookie:

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

如何在 PHP 中获取 cookie:

$_COOKIE["TestCookie"]

本例中的最后一个参数:

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

表示 cookie 只能通过来自客户端的安全 HTTPS 连接传输。当设置为 TRUE 时,只有存在安全连接时才会设置 cookie。在服务器端,程序员只能在安全连接上发送这种 cookie(例如相对于 $_SERVER["HTTPS"])。

来源:https ://secure.php.net/manual/en/function.setcookie.php

于 2016-09-13T05:54:57.810 回答
0

这是错误的,这样做

<script>
   localStorage.setItem('email', "<?php echo $_SESSION['email'];?>");
   localStorage.setItem('password', "<?php echo $_SESSION['password'];?>");
</script>
于 2012-06-06T23:46:41.523 回答
0

您可以通过 PHP 访问本地存储。您需要编写一些在 COOKIE 中存储 localstorage 值的 javascript,您可以使用 PHP 来使用它。

<script>
var email = localStorage.getItem("email");
var d = new Date();
d.setTime(d.getTime() + (1*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = 'email' + "=" + email+ ";" + expires + ";path=/";
</script>
<?php 
print_r($_COOKIE['email']);
?> 
于 2021-12-28T06:30:57.383 回答