简体   繁体   中英

How to save user session in a variable in PHP to be referenced in JavaScript

Case: User clicks on an image

  • If it is a returning user (user session valid for 30 minutes) navigate to the link of the image
  • If it is a new user show a pop-up div

I am now showing the pop-up div whenever the image is being clicked. Any advice on how to save the session and refer it as the variable in a JavaScript to perform a function like:

if {
    // user is log in.. do your task here..
} else {
    //user is not log in.. do your task here...
}

EDIT:

<script>
<? if(isset($_SESSION["logged_in"])) {
    echo "var $check=1";
} else {
    echo "var $check=0";
} ?>

function SetMood() {
    if($check==1) {
        // user is log in.. do your task here..
        alert('URL');
    } else {
        //user is not log in.. do your task here...
        document.getElementById('light').style.display='block';
        document.getElementById('fade').style.display='block';
        document.getElementById('fade').scrollIntoView(true);
    }
}
</script>

This is called for the image as:

<a id="register" href = "javascript:void(0)" onclick = "SetMood();" data-fancybox-group="gallery">
    <img src="<cms:show my_image_thumb />" alt="" class="fade">
</a>

The above has no effect and now nothing opens onClick

Don't perform the conditional check in client-side code, perform it in server-side code.

Assuming you have JavaScript implementations of what you want to achieve, let's call them these respectively:

navigateToLink();
showPopUp();

Then you'd conditionally emit the code for one or the other depending on a server-side session check. Something like this:

<?php
if ($_SESSION['someValue'] == 'someKnownValue') {
?>
    navigateToLink();
<?php
} else {
?>
    showPopUp();
<?php
}
?>

The idea is that server-side code should determine what the user can or can not do. Anything emitted to client-side code is entirely visible to (and modifiable by) the user.

This should help you:

<script>
    var yourValue = '<?php echo $_SESSION['yourSessionValue'] ?>';
    if(yourValue == 'hello') {
        console.log('hide yo kids');
    } else {
        console.log('hide yo wife');
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM