This question already has an answer here:
There have been far too many questions on this subject but I still fail to understand.
Case:
- Hyperlinked image
- OnClick of image: Check if session exists
- If session exist, open link
- If session does not exist, show login form
onclick
is calling a JavaScript function:
var my_global_link = '';
var check = '<?php echo $_SESSION["logged_in"]; ?>';
function show_login( link ) {
if(check == 1)
{
window.location = link;
}
else
{
my_global_link = link;
// .. then show login modal that uses 'js/whitepaper-login.js'
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
document.getElementById('fade').scrollIntoView(true);
}
}
Global variable is being saved in another php file as :
$_SESSION['logged_in'] = 1;
I am unable to capture the session value in the var check
. Can you advise?
Make the request to someone file.php
file.php
Using jQuery here is a simple example of how to get a PHP
$_SESSION
into your JavaScript:session.php
get_session.html (assumes jQuery has been included)
If this is successful you'll see the data and can use it in other JavaScript functions by passing the data appropriately. I often find it handy to
json_encode()
session data, returning JSON to be used by JavaScript, but there is no need to in a simple example such as this one.your javascript is not a very good solution, as it can be hacked easily. One can simply change the value of
check
to whatever one likes, and even without a login one would be able to access the link of the picture.A better implementation would probably be something like:
checklogin.php would then verify the
$_SESSION
variable. If validated, you can useheader("Location: something.html");
to redirect to where you want to bring the user. If not logged in, you can instead redirect to the login page:header("Location: login.php");
@Sarah You have to first call the php file via ajax and set the javascript variable as the result. Since the javascript is a client side scripting language hence it can't read server side PHP script. Hence on click call javascript function
file1.php
sess.php
I have done this using two files. You may have not included session file I guess. Its working fine for me.