1

I have a login area of my site, and on login I set a session variable $_SESSION['logged_in'] = true.

Now I also have lots of forms and things where users can input comments. Obviously in my PHP validation I check the user is logged in simply using the session variable, but I want javascript validation too because I can make the user experience slicker that way.

$("body").on("click", ".submit", function(e){
    e.preventDefault();
    if (user == logged in){
        ...AJAX call to php file....
    }
})

So how do people generally do the bit where I check the user is logged in using javascript? ie if user == logged in

2
  • 1
    First I will mention that you should validate on the backend too. But, to answer the question, you can inject php variables into js... so if you have $loggedIn = true, you can do this is js: if (<?php echo $loggedIn ?>) Commented Mar 28, 2013 at 10:31
  • Is this "the" way people do it? It does get the job done, but I somehow don't really like the mix of javascript and php. Commented Mar 28, 2013 at 10:34

1 Answer 1

1
  • You can of course check user permissions by AJAX (with JSON for example), but this will provide some additional latency.

  • You can just write a value to global JS scope like this:

    if ( userIsLogged() ) { echo "<script>document.mysite.userlogged = true;</script>"; }

    then you can check document.mysite.userlogged variable.

  • You can also set a cookie in PHP, wich can be obtained in JavaScript. To get cookies properly in JS see that: Javascript getCookie functions

  • If you don't want to inject JS code, you can set some attribute like:

    <div id="comments" data-logged="<?php echo $isLogged; ?>"> ... </div>

    And get it by jQuery:

    if ( $("#comments").attr('data-logged') == 1 ) {

  • you can provide logged/notlogged specific functionality for the whole page by generating JS file, like: <script type="text/javascript" src="http://yoursite.com/somefile.php"> and generate it in php dynamically, but be aware of caching !

Personally i would go to data-XXX attribute if tou want to personalize single block, and global JS variable if you check logged condition many times in JS.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this looks great. Can I ask why you might call the variable {document.mysite.userlogged} instead of just {userlogged}?
userlogged can be fine, but be aware of javascript scopes and closures, document.... cleanly signs that we think about global variable. Also if you want to set document.mysite.variable first you must document.mysite = {}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.