检索php值并在javascript中使用它


Retrieve a php value and use it in javascript

在我的网站上,我为会话对象设置了一些值,比如"user_status"、"user_name"等等。php文件如下所示:

<script type="text/javascript">
    var logged = <? echo $this->session->getValueOf("user_status"); ?>;
</script>
<a class="show_message" href="#">SHow my status</a>

好吧,我有一个js脚本,它假装根据网站中的user status执行操作,所以,我有这个:

$('.show_status').click(function(event){
    //ask for user status
    if (logged){
        //do something
    }
    else{
        //do another action for visitors
    }
});

四处走动,我想这是否是在session->javascript之间流动数据的最佳方式,因为如果你在浏览器上检查页面源,user_status的值将是可见的,并且可能会对网站安全造成风险。

提前感谢

编辑:

  1. logged var只接受布尔值
  2. 每次单击元素#(".show_status")时都必须执行js操作

如果JavaScript只是用于接口,并且没有任何后端效果,我可能不会太担心处理客户端逻辑的不安全性。

如果安全性很重要,我建议您使用PHP编写适当的JavaScript函数。例如:

在正在查看的页面上,也许在标题中,您有:

<script type="text/javascript">
    <?php
    if ($this->session->getValueOf("user_status")) {
        require_once('logged_in_user_functions.js');
    } else {
        require_once('visitor_functions.js');
    }
    ?>
</script>

在文件"logged_In_user_functions.js"中,您有:

function showComment(id) {
    //logic that shows the comment here
}
function showCommentSubmissionForm() {
    //logic that adds this form to the page goes here
}

同时,在文件"visitor_functions.js"中,您有:

function showComment(id) {
    //logic that shows the comment in a different way goes here
}
function showCommentSubmissionForm() {
    //logic to display a message saying the user needs to log in to post a comment goes here
}

然后,您可以将逻辑添加到页面中,而无需检查用户状态。js文件所包含的正确行为是:

<button id='add_comment_button' onclick='showCommentSubmissionForm()'>Add Comment</button>

这让PHP(以及服务器,而不是客户端)对向用户显示的内容拥有最终发言权。

假设user_statusActive类似,那么这并不是真正的安全风险。

如果你想隐藏所有,不被随意窥探,你可以尝试使用加密的cookie,使用类似"如何在cookie中保存加密数据(使用php)?"?加密您的价值观。