简体   繁体   English

在JavaScript中访问PHP SESSION值

[英]Access PHP SESSION value in JavaScript

I generate a session value for each visitor on my website. 我为网站上的每个访问者生成一个会话值。 If they submit the form, it sends the data via a jQuery AJAX request to my PHP validator script. 如果他们提交了表单,它将通过jQuery AJAX请求将数据发送到我的PHP验证程序脚本。

This script performs several checks on the data the user submitted. 该脚本对用户提交的数据执行多项检查。 If everything has been validated, it returns a sha256 hash which is generated with the function hash_hmac('sha256', 'success', $_SESSION['secret_key']) . 如果所有内容均已通过验证,则返回使用函数hash_hmac('sha256', 'success', $_SESSION['secret_key'])生成的sha256哈希。 I hash this so users cannot manipulate the response with software such as Charles. 我对此进行了哈希处理,因此用户无法使用诸如Charles之类的软件来操纵响应。

The jQuery request receives the hashed string and I have to hash 'success' with the secret key again to check if they match. jQuery请求收到散列的字符串,我必须再次用密钥对“成功”进行散列,以检查它们是否匹配。 However, the secret key is stored in a PHP session and I am not able to figure out how to get access to it through JavaScript. 但是,秘密密钥存储在PHP会话中,我无法弄清楚如何通过JavaScript对其进行访问。

An AJAX request to a PHP script would not be ideal — an attacker can then edit the response to make it match with their own hashed strings. 对PHP脚本的AJAX请求并不理想-攻击者可以编辑响应以使其与自己的散列字符串匹配。

I'll simply elaborate on my comments in this answer. 我将仅在此答案中详细说明我的评论。

You say 你说

An AJAX request to a PHP script would not be ideal — an attacker can then edit the response to make it match with their own hashed strings. 对PHP脚本的AJAX请求并不理想-攻击者可以编辑响应以使其与自己的散列字符串匹配。

They can edit the response, but if it's all done client side, they can still edit it. 他们可以编辑响应,但是如果已全部在客户端完成,他们仍然可以对其进行编辑。

You want to send the data hashed, then you want the client to be able to check the hash, so I'm not sure what the point in hashing would be, other than security in transport. 您要发送散列的数据,然后希望客户端能够检查散列,所以我不确定散列的意义是什么,除了传输的安全性。 I can't tell you what you really need, because I'm not seeing the use case here. 我无法告诉您您真正需要什么,因为这里没有看到用例。

I do know you'll either need to go to the server for something you want to keep secret from the client. 我知道您要么需要进入服务器,要么想向客户端保密。 There's no security on the client side. 客户端没有安全性。

As long as you are using javascript in your php file, something like this will suffice... 只要您在php文件中使用javascript,像这样的东西就足够了...

<script>  
   var secret_key = <?php echo json_encode($_SESSION['secret_key']); ?>  
<script>  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM