I discovered that the PHP session ID is stored in a cookie. It appears in the cookie string as "...;PHPSESSID=fkldsjflksjlf;...". In my Javascript XMLHttpRequest script, I use the following to extract the session ID from the cookie. Then I send it as a parameter.
function test() {
var idBegin = document.cookie.indexOf("PHPSESSID=") + 10;
var sessId = document.cookie.substring(idBegin)
var idEnd = sessId.indexOf(";");
sessId = sessId.substring(0, idEnd);
var request = new XMLHttpRequest();
request.open("GET", "test.php?sessid="+sessId, true);
request.onreadystatechange = function () {
if (request.readyState === 4) {
if ((request.status === 200) || (request.status === 0)) {
}
}
};
request.send(null);
}
On the server side, I have a table "UserSessions" in my MySQL database. The table has two columns: SessionID; and UserID. I have a PHP script that executes when the user loads a page. At this point, the get_current_user_id() function is available to get the WordPress user ID and $_COOKIE["PHPSESSID"] is available. The PHPSESSID is what's stored as a cookie on the client.
<?php
$sql = "INSERT INTO UserSessions (SessionID, UserID)";
$sql = $sql . " VALUES (" . $_COOKIE["PHPSESSID"] . ",";
$sql = $sql . get_current_user_id() . ")";
// I user the standard MySQLi stuff to execute the query and
// store the session ID, user ID pair
?>
In PHP the scripts I execute via Javascript, I include the following
<?php
$sql = "SELECT UserID FROM UserSessions ";
$sql = $sql . " WHERE SessionID = " . $_GET["sessid"];
// Again, standard MySQLi stuff to execute the query
// and retrieve the user id based on the session ID.
// I store the retrieved value in variable "$userid"
// When I have the user id, I can use it in other tables
// that have a UserID column
$sql = "SELECT column FROM table ";
$sql = $sql . " WHERE UserID = " . $userid;
$sql = "INSERT INTO table (column) VALUES (data) ";
$sql = $sql . " WHERE UserID = " . $userid;
?>
This doesn't seem like the right way to do it. It works for me. And I don't know how to do it better. By all means, tell me it's incorrect and give me the correct way to do this. Thanks.