Triggering Or Preventing A Javascript Function If $_session['sess_user_id'] Isn't Set
Solution 1:
Adding on to techfoobar's answer...
It is generally a good practice to put your variables from PHP into Javascript (if needed) and letting Javascript handle it, as opposed to echoing different javascript depending on a PHP variable.
Keep in mind that all javascript variables CAN be manipulated by the client.
Try something like this:
if(!isset($_SESSION['SESS_USER_ID']) || (trim($_SESSION['SESS_USER_ID']) == '')){
$t="no_session";
}
else{
$t="yes_session";
}
....
<script>var session="<?phpecho$t; ?>";
if(session == "no_session")
loginFailed();
</script>
Solution 2:
PHP runs on the server side. JavaScript runs on the client side inside the browser. PHP cannot directly invoke JavaScript functions.
PHP can however render JavaScript along with the HTML to the browser so that the browser can in turn run it.
In your particular case, one thing you can do is check for logged-in status via an AJAX call and call the required JS methods on its success callback.
Example:
For checking the login status:
/* JS */functioncheckLoginState() {
$.post('/yourserver.com/isloggedin.php', function(data) {
if(data != "OK") { // not logged in// call your JS method thats disables stuff etc.
loginFailed();
}
});
}
// Periodically check login state
setInterval(checkLoginState, 10000); // check every 10 seconds, change as needed./* PHP - isloggedin.php */if(!isset($_SESSION['SESS_USER_ID']) || (trim($_SESSION['SESS_USER_ID']) == '')){
echo"NOT OK";
}
else {
echo"OK";
}
Solution 3:
I combined @hellohellosharp's suggestion with a solution which was given to me by @willoller for another problem and figured it out :-)
Add this to the php:
$logged_in = (isset($_SESSION['SESS_USER_ID']));
Add this to the javascript:
<?phpif ($logged_in) : ?><aclass="fancybox"data-fancybox-type="iframe"href="iframe1.html"></a><?phpelse : ?>
loginFailed();
<?phpendif; ?>
I'm also using this to change the menu options based on whether or not a user's logged in.
Just a reminder - this uses ISSET to determine what javascript should show, but it only changes the user's experience and doesn't provide any security.
Post a Comment for "Triggering Or Preventing A Javascript Function If $_session['sess_user_id'] Isn't Set"