如何将PHP中的sessionStorage连接到JS [英] How to connect between the sessionStorage in PHP to JS

查看:1588
本文介绍了如何将PHP中的sessionStorage连接到JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在PHP(html)页面中传输数据,因为HTML已加载,因此我可以在页面加载到我的JS文件后处理它。
我的php看起来像这样:

I am trying to transfer data in my PHP (html) page, befor the HTML is loaded, so I will be able to deal with it after the page is loaded in my JS file. my php look like this:

<?php
/*some php code*/
$dataFromDataBase = "..";
session_start();
$_SESSION['data'] = $dataFromDataBase;

if(isset($_SESSION['data']))
    echo $_SESSION['data'];
else
    echo "<br>False";       
?>
<html>
<!--My Html code..-->
</html>

if条件现在检查会话是否在php中创建。
现在它回应我的数据,所以会话存在。
我的JS看起来像这样:

the "if" condition is there now to check if the session was created in the php. now it echo me the data, so it's meen the session exist. my JS look like that:

if(sessionStorage.getItem("data")){
//do some thing..
}else{
alert("the data isn't set.");
}

且数据不存在...我已经踩到警报数据,它发给我null..
他们让我直接输出到JS:

and the data isn't exist... I've tride to alert the data, and it send me "null".. they offered me to output into JS directly like that:

<script>
var fromserver="<?php
/*some code.. */
echo "**BIG DATA**";
?>";

但它只是凌乱的代码..而且数据非常大所以我不能使用coockies

but it is just untidy code.. and the data is pretty big so I can't use coockies

推荐答案

从用户提供的数据创建可执行JS代码是一个主要的安全问题,所以你应该避免像<$ c $这样的语句c> var someJsVar ='<?= $ somePhpVar;?> ;;'。注入恶意代码可能很简单,如';恶意代码 - 这里//

Creating executable JS code from user provided data is a major security issue, so you should avoid the statements like var someJsVar = '<?= $somePhpVar;?>;'. Injecting malicious code could be a simple as '; malicious-code-here //

https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)
https://www.owasp.org/index.php/XSS_Attacks

让页面在页面加载时进行API调用会更安全,这将返回编码为JSON的 sessionStorage 的数据。这样浏览器将看到包含用户数据的变量,而不是原始数据本身。

It would be more secure to have your page make an API call on page load, which would return your data for sessionStorage encoded as JSON. This way the browser will see a variable containing the user data, and not the raw data itself.

#Initial page
<body>
    <script>
         $.GET("/session-storage.php").success(function(response){
             sessionStorage.setItem("data", response);
         });
    </script>
</body>


#API Call (session-storage.php)
<?php
    $dataFromDataBase = "..";

    echo json_encode($dataFromDataBase);
?>

这篇关于如何将PHP中的sessionStorage连接到JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆