0

I want to send the value of my PHP session variable to JavaScript in the same file. I tried this code, but it doesn't work. Please help me resolve the issue.

Here is what I am trying :

<?php
session_start();
?>

<h2>
<?php
echo "Welcome, " .$_SESSION["name"];
?>
</h2>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="chat.js"></script>
</head>
<body onload="init();">
<noscript>
Your browser does not support Javascript!!
</noscript>

<!-- Some HTML Code -->

<div>
    <a href="../index.php">Go back</a>
    <a href="../home.php?SignOut" id= "left">Sign Out</a>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
    $("#left").click(function() {
                //remove user_name. Set action: left
                var user_name = <?php echo json_encode($_SESSION["name"]) ?>;
                $.post('php/users.php', {user_name: user_name, action: 'left' });

            });
});
</script>
</div>  

</body>
</html>

This is my users.php file

if(isset($_POST['user_name'], $_POST['action'])) {
    $user_name = $_POST['user_name'];
    $action = $_POST['action'];

    if($action == 'joined') {
        user_joined($user_name);
    }
}


else if(isset($_POST['action'])) {
    $action = $_POST['action'];

    if($action == 'list') {
        foreach(user_list() as $user) {
            $link_address = "Chat/index.php";
            echo '<a class="a" name="a" href='.$link_address.'>'.$user.'</a>';
            echo '<br />';
        }
    }
    else if($action == 'left') {
        //call user_left function
        user_left();
    }

}

function user_left() {
    $servername = "";
    $username = "";
    $password = "";
    $dbname = "";

    //Create connection

    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    }

    $user_name = $_SESSION["name"];


    $sql = "DELETE FROM online_users WHERE user_name = '$user_name'";
    $query = "DELETE FROM chat WHERE to_user = '$user_name'";

    $result = $conn->query($query);

    if($conn->query($sql) === TRUE) {
        echo "Record deleted successfully";
    } else {
        echo "Error in deleting: " . $sql. "<br>" . $conn->error;
    }


    $conn->close();
}
12
  • What's php/users.php (with these parameters) exactly do ? Commented Sep 21, 2015 at 19:24
  • @Michel php/users.php deletes the user from the mysql table who clicked on Sign Out, if the action is left. Commented Sep 21, 2015 at 19:28
  • The php being called should be reading the username from the session itself rather than trusting a post parameter Commented Sep 21, 2015 at 19:29
  • 1
    @Kashish : so if I replace the value of user_name client side (for example with Firebug), I could delete another user if I know his user_name ? Commented Sep 21, 2015 at 19:33
  • 1
    $.post('php/users.php', { action: 'left' }); server already knows who the user is Commented Sep 21, 2015 at 19:41

3 Answers 3

1

First of all you have to look in debug console for errors (usualy it can be opened with F12 key). I see a problem in your code: php echo statement has to be in outer quotes, because it is interpreted as a string in JS:

var user_name = "<?php echo $_SESSION["name"] ?>";

Just open console and you will see exact line and character where the error is.

Other way of passing variables from PHP to JS is cookies.

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

1 Comment

Well, I missed json_encode in your code. It could work without quotes. Other suggestions do work well :)
0

Turned out to be a silly mistake. Sorry for troubling you all guys.

I figured out the error. I was able to read php sessions in JS (Figured that out when I inspected element on chrome). But, I guess that wasn't required and I just used the

$.post('php/users.php', { action: 'left' }); 

Rather than trusting the post parameter on username, I used sessions variables. The main issue was that I was not able to delete the username in the user.php file and I figured out that because I used

$.post('php/users.php', { action: 'left' }), 

I am actually not sending any user_name in the post parameter. My call to user_left function was in the if condition where I was checking

if (isset $_POST[user_name] && $_POST[action]), 

and therefore, I couldnt call user_left function.

This was my code earlier

if(isset($_POST['user_name'], $_POST['action'])) {
    $user_name = $_POST['user_name'];
    $action = $_POST['action'];

    if($action == 'joined') {
        user_joined($user_name);
    }
    else if($action == 'left') {
        //call user_left function
        user_left();
    }
}
else if(isset($_POST['action'])) {
    $action = $_POST['action'];

    if($action == 'list') {
        foreach(user_list() as $user) {
            $link_address = "Chat/index.php";
            echo '<a class="a" name="a" href='.$link_address.'>'.$user.'</a>';
            echo '<br />';
        }
    }
}

I changed it to:

if(isset($_POST['user_name'], $_POST['action'])) {
    $user_name = $_POST['user_name'];
    $action = $_POST['action'];

    if($action == 'joined') {
        user_joined($user_name);
    }
}


else if(isset($_POST['action'])) {
    $action = $_POST['action'];

    if($action == 'list') {
        foreach(user_list() as $user) {
            //echo $user, '<br />';
            $link_address = "Chat/index.php";
            echo '<a class="a" name="a" href='.$link_address.'>'.$user.'</a>';
            echo '<br />';
        }
    }
    else if($action == 'left') {
        //call user_left function
        user_left();
    }

}

1 Comment

Still might want to take a look at my answer, because trusting this POST var for username may leave you with a vulnerability.
0

In your main PHP, change:

var user_name = <?php echo json_encode($_SESSION["name"]) ?>;
$.post('php/users.php', {user_name: user_name, action: 'left' });

To:

$.post('php/users.php', { action: 'left' });

Then in users.php change:

if(isset($_POST['user_name'], $_POST['action'])) {
    $user_name = $_POST['user_name'];
    $action = $_POST['action'];

    if($action == 'joined') {
        user_joined($user_name);
    }
}

To:

session_start();
if(isset($_SESSION['name'], $_POST['action'])) {
    $user_name = $_SESSION['name'];
    $action = $_POST['action'];

    if($action == 'joined') {
        user_joined($user_name);
    }
}

Why? Because you already have a session with the user logged in, so the user_name is in the session. The safest place to retrieve it from will always be the session. If you print the user_name from session to your HTML/Javascript code and have it sent back roundtrip to the server in a POST parameter, and trust that parameter, then the user could have changed the username in his browser's developer tools (or some other way) to someone else'se user_name to log them out (or even impersonate them in the chat via your user_joined method). You'd be creating a security hole. So don't send the user_name roundtrip: just read it from the session on the server-side.

Also, be sure to be consistent on whether its $_SESSION["name"] or $_SESSION["user_name"].

Comments

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.