How to read a session variable from a php file in

2019-08-06 12:36发布

问题:

This question already has an answer here:

  • How do I pass variables and data from PHP to JavaScript? 18 answers

There have been far too many questions on this subject but I still fail to understand.

Case:

  1. Hyperlinked image
  2. OnClick of image: Check if session exists
  3. If session exist, open link
  4. 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?

回答1:

Using jQuery here is a simple example of how to get a PHP $_SESSION into your JavaScript:

session.php

<?php
    session_start();
    $_SESSION['foo'] = 'foo';
    echo $_SESSION['foo']; // this will be echoed when the AJAX request comes in
?>

get_session.html (assumes jQuery has been included)

<script>
    $(function() {
        $('a').click(function(event){ // use instead of onclick()
            event.preventDefault(); // prevents the default click action

            // we don't need complex AJAX because we're just getting some data
            $.get('session.php', function(sessionData) {
                console.log( sessionData ); // session data will be 'foo'
            });
        });
    });
</script>

<a href="session.php">click</a>

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.



回答2:

Make the request to someone file.php

$( document ).ready(function(){//run when DOM is loaded
  $.post("file.php",  //make request method POST to file.php
     function(data){  //callback of request is data
      var arr = jQuery.parseJSON(data); //make json decoding
      if(arr.logged == 1)   //arr.logged is value needs
       #do 
     })
 })

file.php

<?php
 session_start(); //start session for my dear friend Jay Blanchard
 $_SESSION['logged_id'] = 1; //init value for example
 $array = array('logged' => $_SESSION['logged_id']);//creat array for encoding
 echo json_encode($array); //make json encoding for call back
?>


回答3:

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:

<a href="checklogin.php"><img src="img.png" alt="" /></a>

checklogin.php would then verify the $_SESSION variable. If validated, you can use header("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");



回答4:

@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

function someFunc(){
    //Fire Ajax request 
    //Set check variable 
    //and perform the function you want to ...
}


回答5:

<?php include "sess.php"; ?>
<script type="text/javascript">
var my_global_link = 'testr.com';
var check = '<?php echo $_SESSION["logged_in"]; ?>';

function show_login( link ) {

 if(check == 1)
 {
     window.location = link;
 }
 else
 {
     my_global_link = link;  

        document.getElementById('light').style.display='block';
        document.getElementById('fade').style.display='block';
        document.getElementById('fade').scrollIntoView(true); 
     }

    }

     </script> 
    <a href="#" onclick="show_login('test')" >test</a>

file1.php

   <?php 
   session_start();
   $_SESSION["logged_in"] = 1;
   ?> 

sess.php

I have done this using two files. You may have not included session file I guess. Its working fine for me.