manix
manix

Reputation: 14747

Retrieve a php value and use it in javascript

In my website I set some values to session object like "user_status", "user_name" and like so. The php file looks like this:

<script type="text/javascript">
    var logged = <? echo $this->session->getValueOf("user_status"); ?>;
</script>

<a class="show_message" href="#">SHow my status</a>

Well, I have a js script that pretends do an action according to user status in the website, so, I have this:

$('.show_status').click(function(event){

    //ask for user status
    if (logged){
        //do something
    }
    else{
        //do another action for visitors
    }
});

Walking around I thought if it is the best way flow data between session -> javascript, because if you inspect the page source at browser the value of user_status will be visible and could be riskable for website security.

Thanks in advance

EDIT:

  1. logged var only takes a boolean value.
  2. The js action must be executed each time the element #(".show_status") is clicked.

Upvotes: 3

Views: 121

Answers (2)

Michael Fenwick
Michael Fenwick

Reputation: 2494

If the JavaScript is just being used for interface stuff, and doesn't have any back end effects, I probably wouldn't worry too much about the insecurity of handling that logic client-side.

If security is an important thing though, I would recommend you use PHP to write the appropriate JavaScript function. For example:

On the page being viewed, perhaps in the header, you have:

<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>

In the file `logged_in_user_functions.js' you have:

function showComment(id) {
    //logic that shows the comment here
}

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

Meanwhile, in the file `visitor_functions.js' you have:

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
}

Then you can add your logic into your page without having to check the user status. The proper behaviour is provided by virtue of which .js file was included:

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

This gives PHP (and thus the server, not the client) final say in what gets displayed to the user.

Upvotes: 3

Michael Robinson
Michael Robinson

Reputation: 29498

Assuming that user_status will be something like Active, then this isn't really a security risk.

If you want to hide everything from casualy prying eyes, you could try using an encrypted cookie, using something like How to save encrypted data in cookie (using php)? to encrypt your values.

Upvotes: 2

Related Questions