PHP: session_start() doesn't work on Server, but on localhost? - php

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

Related

Sessions doesn't working

Hi i have a problem with the use of session.
I create the session here
<?php session_start();
include('MConsultas.php');
$mail = $_POST['mail'];
$contraseña = $_POST['contraseña'];
$Objeto = new Consulta();
$consulta="SELECT * from persona where Email='".$mail."'";
$Rset = $Objeto->querys($consulta);
if ($fila = mysql_fetch_assoc($Rset)) {
$contraseña1=hash('sha512',$contraseña);
if ($fila['Contrasena']==$contraseña1)
{
$_SESSION['IDuser']= $fila['ID_Persona'];
$_SESSION['IDnombre']= $fila['Nombre'];
$_SESSION['IDemail']= $fila['Email'];
$_SESSION['IDempre']= 'NULL';
$_SESSION['IDAbogado']= 'NULL';
$_SESSION['Autentica'] = "si";
$_SESSION['Tipo']="persona";
echo $fila['ID_Persona'];
echo "<script type='text/javascript'> document.location = '../administrador/personas/mis-casos.php'; </script>";
}
And i try to use the session here:
<?php session_start();
if($_SESSION['Autentica'] == 'si')
{
if($_SESSION["Tipo"] == "persona" || $_SESSION["Tipo"] == "empresa")
{
?>
But this php, doesn't recognize the session.
Can someone tell me what i'm doing wrong please?

PHP logging out by using class

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

Strange Password_Hash Issue

So im using the exact same script as I used to a while back and for some reason when I move to my new domain and hosting it is having really weird issues, I created a user and got hm to try login, It wasnt working for him I got a new hash from a random test.php file with this php:
<?php
/**
* In this case, we want to increase the default cost for BCRYPT to 12.
* Note that we also switched to BCRYPT, which will always be 60 characters.
*/
$options = [
'cost' => 9,
];
echo password_hash("His Pass", PASSWORD_BCRYPT, $options)."\n";
?>
It then worked, He logged in fine and I then tried to login to my main admin account and for some reason its now not working even when I try remaking the hash 2 times now.
I have no idea whats going on can someone please enlighten me.
Heres the login code:
//If User Submits Form continue;
if(isset($_POST['username'])) {
//If the captcha wasn't submitted;
if(empty($_POST['g-recaptcha-response'])) {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "nocaptcha");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "nocaptcha");</script> <?php
}
//If the captcha was submitted;
} else {
//Set captcha variable to the Submitted Captcha Response;
$captcha=$_POST['g-recaptcha-response'];
//Captcha Verification Url;
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=t&response=';
//JSON Encode the Captcha's response and Site IP;
$response = json_decode(file_get_contents($url.urlencode($captcha).'&remoteip='.$_SERVER['REMOTE_ADDR']), true);
//If the captcha wasn't verified;
if($response['success'] == false) {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "captchafailed");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "captchafailed");</script> <?php
}
//Otherwise if it was verified;
} else {
//Try log in with the given details;
user_login($_POST['username'],$_POST['password']);
//If logged in redirect and give a notification;
if(loggedin()) { ?>
<script type="text/javascript">localStorage.setItem("notification", "loggedin");</script>
<meta http-equiv="refresh" content="0;URL='https://gameshare.io'" /> <?php
} else {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "loginfailed");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "loginfailed");</script> <?php
}
}
}
}
}
User_login function:
//Create a new function named user_login;
function user_login($username = false, $password = false) {
//Fetch for the username and password applied;
$st = fetch("SELECT username,password,email,image FROM users WHERE username = :username",array(":username"=>$username));
//If a row was found continue
if($st != 0) {
$storedhash = $st[0]['password'];
if (password_verify($password, $storedhash)) {
//Set a new username session and set it the username;
$_SESSION['username'] = $username;
$_SESSION['email'] = $st[0]['email'];
$_SESSION['image'] = $st[0]['image'];
if($username == 'admin') {
$_SESSION['role'] = 'admin';
} else {
$_SESSION['role'] = 'user';
}
}
}
//If no errors happened Make the $valid true;
return true;
$dontaddtry = true;
}
Fetch function:
//Create a new function named fetch;
function fetch($sql = false,$bind = false,$obj = false) {
//Prepare The SQL Query;
$query = Connect()->prepare($sql);
//Execute Binded Query;
$query->execute($bind);
//While Fetching Results;
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
//Add a row to the results respectiveley;
$row[] = $result;
}
//If there are no rows;
if(!empty($row)) {
//Make it an object;
$row = ($obj)? (object) $row : $row;
} else {
//Else row is false;
$row = false;
}
//If no errors happened Make $row true;
return $row;
}
Connect Function:
//Create a new function named LoggedIn, And apply database info;
function Connect($host = 'localhost',$username = 'x',$password = 'x',$dbname = 'x') {
//Try execute the PHP with no errors;
try {
//Create a PDO Session;
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
//Session Attributes;
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
//Catch all PDOException errors;
catch (PDOException $e) {
//If any errors print result;
echo "<code><pre>".print_r($e)."</pre></code>";
//Make the PDO session false;
$con = false;
}
//If no errors happened Make the PDO session true;
return $con;
}
P.S If you wish to get an account to try on my site let me know and ill make a temporary account.
Make sure your the php version of your new hosting. password_hash needs at-least PHP 5.5.0.
You can check your current PHP version via following code.
<?php
echo 'Current PHP version: ' . phpversion();
?>

PHP $_SESSION returning incorrect value

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!!

get names of online users

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.

Categories