Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 615
manix Avatar asked Sep 17 '26 06:09

manix


1 Answers

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.

like image 69
Michael Fenwick Avatar answered Sep 19 '26 19:09

Michael Fenwick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!