I need some help on my log out. I try to show less code as possible to avoid long code.
What I'm trying to do is a webpage that allow user to log in and view some stuff. When the user done viewing the stuff, the user are able to log out. When logging out, it'll redirect the user to login page and update my database to clear up all the data such as session_id etc.
But the problem is, whenever the user click the log out button, it'll redirect the user to the login page, but not updating the query which is in the logout function. I'm trying to logs the user out by clearing all the session and data in the database such as session_id, last_log, etc.
Is there any way to make the log out button works?
In my protect class
class protect
{
var $username = "";
var $password = "";
var $id = "";
var $isAdmin = -1;
var $sess_id = "";
var $action = "";
var $query = "";
var $ip_address = "";
var $otp = "";
function __construct()
{
try
{
session_start();
$db = new DB("XXUser","password",DB_NAME);
$db->connect();
$this->check_login($db);
if(!isset($_SESSION['loggedin']) || $_SESSION['loggedin']!=1)
{
$this->logout($db);
}
else
{
if($this->action == "logout")
{
$this->logout($db);
}
$this->check_session($db);
}
}
catch
{
$this->logout($db);
exit();
}
}
function post_value()
{
if (!empty($_POST))
{
foreach ($_POST as $key => $value)
{
$this->$key=$value;
}
}
}
function get_value()
{
if(isset($_GET['action']))
{
$this->action=$_GET['action'];
}
}
function insert_session($db)
{
$sql = "UPDATE myuser SET lastLog = now(), active = 'Y', last_active
= now(), last_access = now(), ip_addr = '".$this->ip_address."',
session_ID = '".trim($this->sess_id)."', fail_login_count = 0,
last_fail_login_time ='1900-01-01 00:00:00', otp =
'".$_SESSION['otp']."' WHERE ID = '".$_SESSION['id']."'";
$db->query($sql);
}
function check_session($db)
{
if(isset($_SESSION['loggedin']) || $_SESSION['loggedin'] == 1)
{
$sql2 = "SELECT * FROM myuser WHERE ID = '".$_SESSION['id']."'
AND otp = '".$_SESSION['otp']."'";
$db->query($sql2);
$db->fetchRow();
if($db->resultCount() == 0)
{
echo "<script type=\"text/javascript\">
alert(\"Access Denied\");
</script>";
session_destroy();
$db->disconnect();
header("Location: login2.php");
exit();
}
else
{
$this->check_time($db);
$this->refresh_session();
}
}
}
function refresh_session()
{
//Regenerate id
session_regenerate_id();
//Regenerate otp
$_SESSION['otp'] = trim(md5(time() .$_SESSION['id']));
}
function check_time($db)
{
$sql3 = "SELECT * FROM myuser WHERE ID = '".$_SESSION['id']."' AND
otp = '".$_SESSION['otp']."' AND last_active > DATE_SUB(NOW(),
INTERVAL 10 MINUTE)";
$db->query($sql3);
if($db->resultCount($db) == 0)
{
$this->logout($db);
}
else
{
$sql2 = "UPDATE myuser SET last_active = now() WHERE ID =
'".$_SESSION['id']."' AND otp = '".$_SESSION['otp']."'";
$db->query($sql2);
}
}
function check_login($db)
{
if(!isset($_SESSION['loggedin']) || $_SESSION['loggedin']!=1)
{
$this->username = sanitize($_POST['username']);
$this->password = $_POST['password'];
$sql = "SELECT * FROM myuser WHERE userName = '".$this-
>username."' AND userPass = '".$this->password."'";
$db->query($sql);
if($db->resultCount() == 0)
{
echo "<script type=\"text/javascript\">
alert(\"Wrong Username or Password\");
</script>";
$db->disconnect();
$db->clear();
}
else
{
$db->fetchRow();
//Correct username but wrong password.
if($db->record['userName'] == $this->username)
{
if($db->record['userPass'] != $this->password)
{
echo "<script type=\"text/javascript\">
alert(\"Wrong Username or Password\");
</script>";
$sql3 = "UPDATE myuser SET ip_addr='".$this-
>ip_address."',fail_login_count=(fail_login_count+1)
WHERE userName='".$this->username."'";
mysql_query($sql3) or die(mysql_error());
}
else
{
$this->id = $db->record['ID'];
$sql4 = "SELECT * FROM subordinate_reporting WHERE
myuser_uid = '".$this->id."'";
$db->query($sql4);
if($db->record['active'] == 'Y')
{
session_destroy();
$db->disconnect();
header("Location: login2.php");
exit();
}
else if($db->resultCount() == 0)
{
echo "<script type=\"text/javascript\">
alert(\"".$db->record['real_name'].", You
are not authorized to access this page\");
</script>";
$db->clear();
}
else
{
echo "<script type=\"text/javascript\">
alert(\"Welcome ".$db-
>record['real_name'].". Your last access was
on ".$db->record['last_access']."\");
</script>";
$this->session($db);
}
}
}
}
}
}
//This function haven't use
function check_attempt($db)
{
$db->query("SELECT fail_login_count, last_fail_login_time FROM
myuser WHERE userName = ".$this->username."");
$db->fetchRow();
if($db->record['fail_login_count'] >= 3)
{
$db->query("UPDATE myuser SET blocked = 'Y',
last_fail_login_time = now()");
echo "<script type=\"text/javascript\">
alert(\"Your account has been blocked for 10 minutes due to
failed login attempts of 3 times\");
</script>";
}
if($db->record['blocked'] === 'Y')
{
if(($db->record['last_fail_login_time'] - time()) > 10)
{
$db->clear();
$db->query("UPDATE myuser SET last_fail_login_time = '1900-
01-01 00:00:00', fail_login_count = 0, blocked = 'N'");
}
else
{
$db->clear();
echo "<script type=\"text/javascript\">
alert(\"Please try again later\");
</script>";
}
}
}
function logout($db)
{
$sql = "UPDATE myuser SET session_ID = '', otp = '', active =
'N', last_active = '1900-01-01 00:00:00', lastLog = '1900-01-01
00:00:00' WHERE ID = ".$_SESSION['id']." AND
otp='".$_SESSION['otp']."'";
$db->query($sql);
echo $sql;
unset ($_SESSION['otp']);
unset ($_SESSION['loggedin']);
unset ($_SESSION['id']);
session_unset();
session_destroy();
$db->clear();
$db->disconnect();
header("Location: login2.php");
exit();
}
function session($db)
{
$_SESSION['loggedin'] = 1;
$_SESSION['id'] = $this->id;
$_SESSION['otp'] = trim(md5(time() .$_SESSION['id']));
$this->ip_address = $this->get_ip();
$this->sess_id = session_id();
$_SESSION['timeout'] = time();
$this->insert_session($db);
}
function logout_btn()
{
echo "<form name='logoutbtn' method='post' action=''>";
echo "\n <input type='hidden' name='action' value='logout'
/>";
echo "<input type='submit' id='button' value='Log Out' />";
echo "\n</form>";
}
function get_ip()
{
if(getenv('HTTP_CLIENT_IP'))
{
$ip = getenv('HTTP_CLIENT_IP');
}
else if(getenv('HTTP_X_FORWARDED_FOR'))
{
$ip = getenv('HTTP_X_FORWARDED_FOR');
}
else
{
$ip = getenv('REMOTE_ADDR');
}
return $ip;
}
}
In my normal html file
<?php
try
{
$prot = new protect();
if(!isset($_SESSION['loggedin']) || $_SESSION['loggedin']!=1)
{
echo "<script type=\"text/javascript\">
alert("Access Denied");
</script>";
}
}
catch (Exception $e)
{
$e->getMessage();
}
?>
<!DOCTYPE html>
<html>
</html>
<head>
</head>
<body>
$ved = new view_exit_docket($db, $_SESSION['id']);
$ved->check_app_uid($db);
$ved->display_table($db);
$prot->logout_btn();
</body>
</html>
If the log out button was not working, then surely you would not have been redirected - this implies that failures are occurring elsewhere.
I will assume that some of the stuff you have edited out of your code is critical to its operation (other wise it would not behave as you describe).
it'll redirect the user to the login page, but not updating the query
From the code you've shown us, the only route to the redirection is through executing the query. If the data was not changed, then the query failed.
1) You didn't tell us anything about the DB class.
2) You don't check the return value from $DB->query() nor poll the state of the operation from $DB after executing the query. If you had, you might have got an error message explaining the problem.
3) You didn't show us the SQL you are running (the most likely place where the fault lies).
4) You have not said what happened to the session data
Related
I am trying to make a website that echos out a number or a word based on some conditions. I connected it to my database, but it always echos out 2 (user not found), instead of yes100 (password and username correct).
The weird thing is, it works on my main domain, where it outputs yes100, but here it just can not do that for some reason.
I am sure my database details are correct, and I have uploaded the file where it should be.
This is my code (not secure at all, but it is for personal use only.)
$result = $link->query($sql);
if ($result->num_rows > 0) {
// Outputting the rows
while($row = $result->fetch_assoc())
{
$password = $row['password'];
$salt = $row['salt'];
$plain_pass = $_GET['password'];
$stored_pass = md5(md5($salt).md5($plain_pass));
function Redirect($url, $permanent = false)
{
if (headers_sent() === false)
{
header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);
}
exit();
}
if($stored_pass != $row['password'])
{
echo "BLAHAHAHAHAHAHAHAHA";
exit();
}
else
{
echo "yes"; // Correct pass
}
if (strlen($row['hwid']) > 1)
{
if ($hwid != $row['hwid'])
{
echo "0"; // Wrong
}
else
{
echo "100"; // Correct
}
}
else
{
$sql = "UPDATE ". $tables ." SET hwid='$hwid' WHERE username='$user'";
if(mysqli_query($link, $sql))
{
echo "rdy"; // HWID Set
exit();
}
else
{
echo "4"; // Else errors
exit();
}
}
}
}
else
{
echo "2"; // User doesn't exist
exit();
}
?>
I forgot to give the user the permissions. It works now. Thanks everyone.
I searched now for hours but couldn't find any solution. I hope you can help me.
I created a website and tested it with xampp and eververthing works well, but now I uploaded it on a server and I could realize that the session_start() does not work.
This is the code of my index.php:
<?php
session_start();
echo session_status()."<br>";
echo "SessionID: ".session_id();
error_reporting(E_ALL & ~E_NOTICE);
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css" media="screen" />
<meta charset="UTF-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
$(".loginField").click(function() {
$(".loginDetails").toggle("slow");
});
$(".profilName").click(function() {
$(".profilMenu").toggle("slow");
});
$("#middleLoginButton").click(function() {
$(".middleLoginForm").toggle("slow");
});
});
</script>
</head>
<body>
<!-- getting UserData, if available -->
<?php
//delete Session Data, if logout
if (isset($_GET['logout']) && $_GET['logout'] == 1) {
echo "SessionID Logout:".session_id();
session_destroy();
//header("Location:https://www.whocando.eu");
}
function autoload ($className) {
if (file_exists('classes/'.$className.'.php')) {
require 'classes/'.$className.'.php';
}
}
spl_autoload_register("autoload");
if ($_GET['falsePassword'] == 1) {
$falsePassword = 1;
}
if ((empty($_POST['userName']) || empty($_POST['password'])) && empty($_POST['registration'])) {
// after Login Check!
} elseif (isset($_POST['userName']) && isset($_POST['password']) && !isset($_POST['registration'])) {
$loginCheck = new loginParser();
$userID = $loginCheck->loginChecker($_POST['userName'],$_POST['password']);
$_SESSION['userID'] = $userID;
$abfrage = new dbQuery("SELECT ID,name, firstName FROM db764570417.userdata WHERE ID = $userID");
$userName = $abfrage->fetchData('ID','name');
$userFirstName = $abfrage->fetchData('ID','firstName');
// already logged in Check!
} elseif (isset($_SESSION['userID'])) {
$userID = $_SESSION['userID'];
$abfrage = new dbQuery("SELECT ID,name, firstName FROM db764570417.userdata WHERE ID = $userID");
$userName = $abfrage->fetchData('ID','name');
$userFirstName = $abfrage->fetchData('ID','firstName');
// after Registration Check!
} elseif (isset($_POST['registration'])) {
$name = $_POST['name'];
$vorName = $_POST['vorname'];
$email = $_POST['email'];
$uni = $_POST['uni'];
$geburtstag = $_POST['gebDatum'];
$password = $_POST['passwort'];
$confirmedPassword = $_POST['confirmPasswort'];
$gebDatum = date("Y-m-d",strtotime($geburtstag));
$abfrageEmail = new dbQuery("SELECT ID,email FROM db764570417.logindata");
$userEmails = $abfrageEmail->fetchData('ID','email');
if ($password != $confirmedPassword) {
header("Location:https://www.whocando.eu/registration.php?fault=passwordNotMatched&name=".$name."&vorname=".$vorName."&email=".$email."&uni=".$uni."&gebDatum=".$geburtstag);
} elseif (in_array($email,$userEmails)) {
header("Location:https://www.whocando.eu/registration.php?fault=emailAlreadyUses&name=".$name."&vorname=".$vorName."&email=".$email."&uni=".$uni."&gebDatum=".$geburtstag);
} elseif (empty($name)) {
header("Location:https://www.whocando.eu/registration.php?fault=nameMissing&name=".$name."&vorname=".$vorName."&email=".$email."&uni=".$uni."&gebDatum=".$geburtstag);
}elseif (empty($vorName)) {
header("Location:https://www.whocando.eu/registration.php?fault=vorNameMissing&name=".$name."&vorname=".$vorName."&email=".$email."&uni=".$uni."&gebDatum=".$geburtstag);
} elseif (empty($email)) {
header("Locationhttps://www.whocando.eu/:registration.php?fault=emailMissing&name=".$name."&vorname=".$vorName."&email=".$email."&uni=".$uni."&gebDatum=".$geburtstag);
} elseif (empty($uni)) {
header("Location:https://www.whocando.eu/registration.php?fault=uniMissing&name=".$name."&vorname=".$vorName."&email=".$email."&uni=".$uni."&gebDatum=".$geburtstag);
}elseif (empty($geburtstag)) {
header("Locationhttps://www.whocando.eu/:registration.php?fault=gebMissing&name=".$name."&vorname=".$vorName."&email=".$email."&uni=".$uni."&gebDatum=".$geburtstag);
} elseif (empty($password)) {
header("Location:https://www.whocando.eu/registration.php?fault=passwordMissing&name=".$name."&vorname=".$vorName."&email=".$email."&uni=".$uni."&gebDatum=".$geburtstag);
} elseif (empty($confirmedPassword)) {
header("Location:https://www.whocando.eu/registration.php?fault=confirmedPasswordMissing&name=".$name."&vorname=".$vorName."&email=".$email."&uni=".$uni."&gebDatum=".$geburtstag);
} else {
include ('dbConnection.php');
$date = date("Y-m-d H:i:s",time());
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$sqlCode = "INSERT INTO db764570417.logindata (name,email,password)
VALUES (?,?,?)";
$userNameDB = $vorName."".$name;
$statement = $mysqli->prepare($sqlCode);
$statement->bind_Param('sss',$userNameDB,$email,$hashedPassword);
$statement->execute();
$newUserId = $mysqli->insert_id;
$_SESSION['userID'] = $newUserId;
$sqlCode = "INSERT INTO db764570417.userdata (ID,name,firstName,firstLogin,lastLogin,birthDate,email,university)
VALUES (?,?,?,?,?,?,?,?)";
$statement = $mysqli->prepare($sqlCode);
$statement->bind_Param('isssssss',$newUserId,$name,$vorName,$date,$date,$gebDatum,$email,$uni);
$statement->execute();
//header("Location:index.php");
$userID = $newUserId;
$userFirstName[$userID] = $vorName;
$userName[$userID] = $name;
}
}
?>
If I load the page there will be no session ID created, but if I test exactly the same code on localhost, it works.
I thought there were an issue with the server and uploaded a file with the following code:
<?php
if (!isset($_SESSION)) {
session_start();
echo session_status();
echo "SessionID: ".session_id();
}
echo "SessionID: ".session_id();
?>
I am now completely confused and don't know what mistake I did.
Can someone help me with this?
Thank you!
Exec following code and find session.save_path
<?php
phpinfo();
?>
Just add right permissions to this path
My login of admin panel and member panel both works fine on local server, But on Live server member panel doesn't work. As admin and member panel both use same connection file so it means connection file works fine. More over when we fill wrong user or password it says
Invalid User or Password
But when we login with correct user or password it returns back with no indication of error.
My login file upper php part is:
<?php
include_once("../init.php");
$msg='';
?>
<?php
if(isset($_POST['click']))
{
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
if(($user =='' )|| ($pass=='')){
$msg ='Please enter username & password';
}else{
$npass = ($pass);
$qry = mysql_query("select * from user where user ='$user'");
if(mysql_num_rows($qry)==0) {
$msg ='Invalid UserName';
} else {
$res = mysql_fetch_array($qry);
if($res['pass']==$npass) {
$_SESSION['USE_USER'] = $res['user'];
$_SESSION['SID'] = $res['id'];
$_SESSION['USE_NAME'] = $res['fname'];
$_SESSION['USE_SPONSOR'] = $res['sponsor'];
$_SESSION['PACKAGE_AMT'] = $res['package_amt'];
$_SESSION['ADDRESS'] = $res['address'];
$_SESSION['PHONE'] = $res['phone'];
$_SESSION['JOIN_DATE'] = $res['join_date'];
header('location: main.php');
} else {
$msg ='Invalid Password';
}
}
}
}
?>
My header file main.php is
<?php
include_once("../init.php");
validation_check($_SESSION['SID'],MEM_HOME_ADMIN);
$msg='';
$dir ='../'.USER_PIC;
$sId = $_SESSION['SID'];
?>
Session is started from another file called function.php
<?php
function logout($destinationPath)
{
if(count($_SESSION))
{
foreach($_SESSION AS $key=>$value)
{
session_unset($_SESSION[$key]);
}
session_destroy();
}
echo "<script language='javaScript' type='text/javascript'>
window.location.href='".$destinationPath."';
</script>";
}
function validation_check($checkingVariable, $destinationPath)
{
if($checkingVariable == '')
{
echo "<script language='javaScript' type='text/javascript'>
window.location.href='".$destinationPath."';
</script>";
}
}
function realStrip($input)
{
return mysql_real_escape_string(stripslashes(trim($input)));
}
function no_of_record($table, $cond)
{
$sql = "SELECT COUNT(*) AS CNT FROM ".$table." WHERE ".$cond;
$qry = mysql_query($sql);
$rec = mysql_fetch_assoc($qry);
$count = $rec['CNT'];
return $count;
}
//drop down
function drop_down($required=null, $text_field, $table_name, $id, $name, $cond, $selected_id=null)
{
$qry = mysql_query("SELECT $id, $name FROM $table_name WHERE $cond ORDER BY $name ASC");
$var = '';
if(mysql_num_rows($qry)>0)
{
$var = '<select id="'.$text_field.'" name="'.$text_field.'" '.$required.'>';
$var .='<option value="">--Choose--</option>';
while($r = mysql_fetch_assoc($qry))
{
$selected = '';
if($selected_id==$r[$id]){
$selected = 'selected="selected"';
}
$var .='<option value="'.$r[$id].'" '.$selected.'>'.$r[$name].'</option>';
}
$var .='</select>';
}
echo $var;
}
function uploadResume($title,$uploaddoc,$txtpropimg)
{
$upload= $uploaddoc;
$filename=$_FILES[$txtpropimg]['name'];
$fileextension=strchr($filename,".");
$photoid=rand();
$newfilename=$title.$photoid.$fileextension;
move_uploaded_file($_FILES[$txtpropimg]['tmp_name'],$upload.$newfilename);
return $newfilename;
}
function fRecord($field, $table, $cond)
{
$fr = mysql_fetch_assoc(mysql_query("SELECT $field FROM $table WHERE $cond"));
return $fr[$field];
}
function get_values_for_keys($mapping, $keys) {
$output_arr = '';
$karr = explode(',',$keys);
foreach($karr as $key) {
$output_arr .= $mapping[$key].', ';
}
$output_arr = rtrim($output_arr, ', ');
return $output_arr;
}
function getBaseURL() {
$isHttps = ((array_key_exists('HTTPS', $_SERVER)
&& $_SERVER['HTTPS']) ||
(array_key_exists('HTTP_X_FORWARDED_PROTO', $_SERVER)
&& $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
);
return 'http' . ($isHttps ? 's' : '') .'://' . $_SERVER['SERVER_NAME'];
}
function request_uri()
{
if ($_SERVER['REQUEST_URI'])
return $_SERVER['REQUEST_URI'];
// IIS with ISAPI_REWRITE
if ($_SERVER['HTTP_X_REWRITE_URL'])
return $_SERVER['HTTP_X_REWRITE_URL'];
$p = $_SERVER['SCRIPT_NAME'];
if ($_SERVER['QUERY_STRING'])
$p .= '?'.$_SERVER['QUERY_STRING'];
return $p;
}
preg_match ('`/'.FOLDER_NAME.'(.*)(.*)$`', request_uri(), $matches);
$tableType = (!empty ($matches[1]) ? ($matches[1]) : '');
$url_array=explode('/',$tableType);
?>
Moreover I have created user id by words and time like LH1450429882 and column is verture type. I think this has no effect on login.
I think main errors come from function.php Sorry for a long code, but I tried to cover all parts of coding.
I am struggling with this code from a week. Thanks in advance for help.
This is probably a bug that error_reporting will show off. Always use it in development mode, to catch some carelessness errors and ensure the code's clarity.
ini_set('display_errors',1);
error_reporting(E_ERROR | E_WARNING | E_PARSE);
By implementing code ini_set('display_errors',1); error_reporting(E_ERROR | E_WARNING | E_PARSE); I got the error of header ploblem on line 6 in login php I have removed ?> and
Now my working code in login.php is
<?php
include_once("../init.php");
$msg='';
if(isset($_POST['click']))
{
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
if(($user =='' )|| ($pass=='')){
$msg ='Please enter username & password';
}else{
$npass = ($pass);
$qry = mysql_query("select * from user where user ='$user'");
if(mysql_num_rows($qry)==0) {
$msg ='Invalid UserName';
} else {
$res = mysql_fetch_array($qry);
if($res['pass']==$npass) {
$_SESSION['USE_USER'] = $res['user'];
$_SESSION['SID'] = $res['id'];
$_SESSION['USE_NAME'] = $res['fname'];
$_SESSION['USE_SPONSOR'] = $res['sponsor'];
$_SESSION['PACKAGE_AMT'] = $res['package_amt'];
$_SESSION['ADDRESS'] = $res['address'];
$_SESSION['PHONE'] = $res['phone'];
$_SESSION['JOIN_DATE'] = $res['join_date'];
header('location: main.php');
} else {
$msg ='Invalid Password';
}
}
}
}
?>
Ok, so when I execute the initial function it works fine, the username gets stored in the database, however when I run the second function that appends the username to the text the user chooses to enter the IF statement returns 'no user' - when a user is defined...
If anyone knows how to fix this that would be great - I am currently learning PHP and mysql so I am sorry if any of this is incorrect
<?php
session_start()
// connect to the database
mysql_connect("localhost", "root", "");
mysql_select_db("ajaxchat");
// read the stage
$stage = $_POST['stage'];
// primary code
if($stage == 'initial') {
// check the username
$user = $_POST['user'];
$query = mysql_query("SELECT * FROM chat_active WHERE user='$user'");
if (mysql_num_rows($query) == 0) {
$time = time();
//
mysql_query("INSERT INTO chat_active VALUES ('$user', '$time')");
// set the session
$_SESSION['user'] = $user;
echo 'good';
}
else {
echo 'taken';
}
}
/////////////// PROBLEM FUNCTION ///////////////
================================================
else if($stage == 'send') {
// get the textdomain
$text = $_POST['text'];
// check for user_error
if (isset($_SESSION['user'])) {
$user = $_SESSION['user'];
echo $user.' - '.$text.'<br />';
}
else {
echo 'no user';
}
}
else {
echo 'error';
}
?>
This is the javascript:
<script type="text/javascript">
function chat_initialise() {
var user = document.getElementById("chat_user").value;
$.post("./chat.php", {stage:"initial", user:user}, function(data) {
if (data == "good") {
$('#initial').css('display', 'none');
$('#content').css('display', 'inline')
}
else {
alert("That username is taken! Please try another.");
}
});
}
function chat_send() {
var text = document.getElementById("chat_text").value;
$.post("./chat.php", {stage:"send", text:text}, function(data) {
document.getElementById("chat_text").value = '';
$('#window').text($('#window').text() + data);
// alert(data)
});
}
</script>
I fixed it - changed the POST function to take the current username then redefine it as a variable in the second function:
else if($stage == 'send') {
// get the textdomain
$text = $_POST['text'];
$user = $_POST['user'];
echo $user;
// check for user_error
if (isset($_SESSION['user'])) {
$_SESSION['user'] = $user;
echo $user.' - '.$text.'<br />';
}
else {
echo 'no user';
var_dump($_SESSION);
}
}
Thanks for all your help guys!!
as i have mentioned at my earlier post, we are creating a chat for a specific website. Now this chat would have to retrieve the names of the users online and would automatically update once one user would log out of the chat. we were able to create this with the use of PHP alone and right now we are trying to use jquery to avoid often refreshing.so far, this is what we have:
<?php
session_start(); //Configuation
?>
<link rel="stylesheet" type="text/css" href="http://www.pinoyarea.com/videochat/css/winterblues.css">
<?php
$name = $_SESSION['username'];
$room = $_SESSION['room'];
$user = $_SESSION['user'];
if($name == NULL || $room == NULL || $user = NULL)
{
echo "<script>window.location = 'http://www.pinoyarea.com/index.php?p=member/signup';</script>";
}
include "connect.php";
$timeoutseconds = 60; // length of session, 20 minutes is the standard
$timeoutseconds_idle = 30;
$timestamp=time();
$timeout=$timestamp-$timeoutseconds;
$timeout_idle=$timestamp-$timeoutseconds_idle;
$PHP_SELF = $_SERVER['PHP_SELF'];
if (!empty($_SERVER["HTTP_CLIENT_IP"]))
{
//check for ip from share internet
$ip = $_SERVER["HTTP_CLIENT_IP"];
}
elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
{
// Check for the Proxy User
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
else
{
$ip = $_SERVER["REMOTE_ADDR"];
}
$temp = #mysql_query("SELECT * FROM useronline WHERE online_name='$name' AND online_user='$user' AND online_room='$room'");
$rowie = #mysql_num_rows($temp);
// Add this user to database
$loopcap = 0;
while ($loopcap<3){
if($rowie == 0 AND $name != NULL)
{
#mysql_query("insert into useronline values('$timestamp','$ip','$PHP_SELF','$name','$room','$user')");
}
else
{
} // in case of collision
$timestamp = $timestamp+$ip{0}; $loopcap++;
}
// Delete users that have been online for more then "$timeoutseconds" seconds
mysql_query("delete from useronline where timestamp<$timeout");
//Modified
// Select users online
$result = #mysql_query("select distinct online_name from useronline");
$result2 = #mysql_query("SELECT distinct online_name FROM useronline WHERE online_room='$room'");
$user_count = #mysql_num_rows($result2);
mysql_free_result($result);
#mysql_close();
// Show all users online
echo '<table name="tableonline" width="180px">';
if ($user_count==1)
{
echo '<tr><th>';
echo '<font size="1px" style="font-family:arial;"><strong>'.$user_count.' Toozer Online</th></tr>';
}
else
{
echo '<tr><th>'.$user_count.' Toozers Online</strong></font></th></tr></table>';
}
echo "</table><br /><table width='180px'>";
while($cell = mysql_fetch_array($result2))
{
$timestamping = $cell["timestamp"];
if($timestamping >= $timeout_idle && $timestamping < $timeout)
{
$src = "http://www.pinoyarea.com/images/videochat/user-offline.png";
}
else
{
$src = "http://www.pinoyarea.com/images/videochat/user-online.png";
}
echo '<tr><td><img src="'.$src.'"/><font size="1px" style="text-decoration:none;font-family:tahoma;"></td><td>'.$cell["online_name"].'</font>';
echo '<br /></td></tr>';
}
echo '<table>';
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"> </script>
<script>
$(document).ready(function() {
$("#tableonline").load("online_users.php");
var refreshId = setInterval(function() {
$("#tableonline").load('online_users.php?randval='+ Math.random());}, 3000);
});
</script>
//<META HTTP-EQUIV="Refresh" CONTENT="10">
You have to put a boolean value for the user in the DB (in the user table). when he get's login ie when he enter's to his profile page the BOOL value should be changed to 1 and when he get logout change the vlaue to 0.