Нужна помощь с обработкой сеансов. Я использую методы ajax для реализации платформы групповых дискуссий, и во многом ее успех зависит от того, могу ли я правильно обрабатывать сессии, уметь видеть, кто в сети и т. Д. Как я могу сделать это эффективно. Помните, что это типичное ajax-приложение с одним URL, где сервер отвечает только на запрос. Вся проверка формы выполняется на стороне клиента, когда пользователь вводит свои данные. Мне нужна помощь с этим. Ниже того, что написали до сих пор.
<?php
include_once "../database/dbconnect.php";
session_start();
$username = isset($_POST["userNameLogin"]) ? $_POST["userNameLogin"] : $_SESSION["userNameLogin"];
$pwd = isset($_POST["passwordLogin"]) ? $_POST["passwordLogin"] : $_SESSION["passwordLogin"];
// Sending these messages to my client side validation code json-style.
if(!isset($username)){
echo("{message : 'NoName'}");
}
elseif(!isset($pwd)){
echo("{message : 'NoPW'}");
}
// creating the session variables to hold username and pwd
$_SESSION['userNameLogin'] = $username;
$_SESSION['passwordLogin'] = $pwd;
// calling the function incuded above to make connection to mysql db
dbConnection();
//query retrieves username and pwd from db and counts the result. if it is one, then they //certianly exist and if not unset the variables created above. The varibles were created
//above so i do not have to check if they exist before unsetting them.
$sQuery = "SELECT * FROM users WHERE
username = '$username' AND password = '$pwd'";
$result = mysql_query($sQuery) or die(mysql_error());
$intFound = mysql_num_rows($result);
if ($intFound == 0) {
unset($_SESSION['userNameLogin']);
unset($_SESSION['passwordLogin']);
// AD - Access Denied
echo("{message : 'AD'}");
}
else{
//a flag to set in the database who is currently online. value of 1 for users who are //online and zero for users who are not. If i want a list of those online, i check the //column called online and then check to see if the $_SESSION['username'] exist. If it //does then i know the user is online. That is what the second script is for. New to this //stuff, and do not know a better way of doing it
mysql_query("UPDATE users SET online = '1' WHERE username = '$username'") or die(mysql_error);
}
Приведенный выше скрипт должен позволить пользователю войти в систему или запретить доступ, отправив сообщения на код проверки на стороне клиента.
Как видите, я новичок в этом деле, у меня есть доля проблем. Что я могу сделать, чтобы убедиться, что сеансы установлены и отключены правильно, т.е. когда пользователь выходит из системы.
во-вторых, как я могу контролировать, кто в сети, а кто не использует сессии. Вот как я пытаюсь проверить, кто сейчас в сети, а затем создаю файл json с именами пользователей и отправляю его клиенту. Разбираться с джсоном легче.
Сценарий ниже пытается определить, кто в сети
<?php
// this script determines which sessions are currently active by
// 1.) checking to see which online fields in the users table are set to 1
// 2.) by determining if a session variable has been set for these users.
// If it is not set, it means user is no longer active and script sets its online field in the users table to zero.
// After doing this, the script, then queries the users table for online fields with values one, writes them to an
// array and passes them to the client.
include_once "../database/dbconnect.php";
//include "../validation/accessControl.php";
$tempActiveUsers = array();
$activeUsers = array();
$nonActiveUsers = array();
dbConnection();
$sql = "SELECT username from users WHERE online = '1' ";
$active_result = mysql_query($sql) or die(mysql_error);
if($active_result){
while($aValues = mysql_fetch_array($active_result)){
array_push($tempActiveUsers, $aValues['username']);
}
}
forEach($tempActiveUsers as $value){
/*if($_SESSION['$value'] == $value){
$activeUsers += $value;
} */
if(isset($_SESSION['userNameLogin']) == $value){
array_push($activeUsers, $value);
}else{
array_push($nonActiveUsers, $value);
}
}
forEach($nonActiveUsers as $value1){
$sql1 = "UPDATE users SET online='0' WHERE username = '$value1'";
$set_result = mysql_query($sql1) or die(mysql_error);
}
$length = sizeof($activeUsers);
$len = 1;
$json ='{"users" : {';
$json .= '"user":[';
forEach($activeUsers as $value2){
$json .= '{';
$json .= '"username" : "' .$value2.'" }';
if($len != $length){
$json .= ',';
}
$len++;
}
$json .= ']';
$json .= '}}';
echo $json;
Пожалуйста, просмотрите и дайте несколько советов. Это очень порадует. Мой проектный фреймворк работает хорошо, но я могу реализовать много пользовательских функций, потому что не могу отследить, кто в сети и как управлять их сессиями. Если вам нужна дополнительная справочная информация, дайте мне знать. Заранее спасибо