I try to destroy the Session from a other user after I changed his permissions or his ban-status...
I write the session key from every user in to the database and catch them if I visits there Profiles. If there are any changes I want that the User will get kicked out of the System instantly...
Here is my code:
FUNCTION back_to_home() {
mysqli_close($db);
$session_id_to_destroy = $_SESSION['visit_user-session_id'];
session_id($session_id_to_destroy);
session_start();
session_destroy();
unset($_SESSION['visit_user-username']);
unset($_SESSION['visit_user-e_mail']);
unset($_SESSION['visit_user-register_date']);
unset($_SESSION['visit_user-last_login_date']);
unset($_SESSION['visit_user-register_ip']);
unset($_SESSION['visit_user-last_login_ip']);
unset($_SESSION['visit_user-steam_id']);
unset($_SESSION['visit_user-permissions']);
header('Location: ../../../');
exit;
}
I hoped I can fix or do that with PHP. I have no clue of JavaScript xD
So what I want to know is, Can I do that like that or is there another way to kick out another user from his session?
I try to destroy the Session from a other user
You can technically do this, yes, but the process is long winded and problematic.
How to delete an arbitary session.
A: Finding the session
You need to use the session_id value. This value is part of the file name (or in the case of database sessions the session identifier column value).
You need to know the file name precursor (usually sess_ but can be anything as set in the PHP source code). You also need to know the session storage location as set in your PHP.ini file.
Example:
A session with id 58ce93c623376b3ddfca3cfc3a01d57d3be85084363147464 is a file at:
/home/session_storage_folder/sess_58ce93c623376b3ddfca3fc3a01d57d3be85084363147464
But session file names are generated on the fly and are not (and should not be) connected to whose who on your membership database.
If you generate session id's manually then this becomes easier, but the security of sessions becomes greatly reduced and this should really, really not be done without very careful thought.
B: Finding the user
Now you need to find the User that you want to ban. The session file will contain the users id, somehow,
Session data is stored typically as:
(Example)
$_SESSION['alpha'] = "UiOvMfV9byatH4Wt1SPYUO3zgsj5";
$_SESSION['beta'] = 1324;
alpha|s:28:"UiOvMfV9byatH4Wt1SPYUO3zgsj5";beta|i:1324;
Which is
[var name]|[var type]:[var contents length]:[contents data]; [etc....]
So if you had a user id value set as $_SESSION['user_id'] = 45; this would be:
user_id|i:45;
In the session. So you would need to search every session you had for this data string.
Please read this question about how to do this
So you would have code like this:
$string = 'user_id|i:".(int)$user_id_to_block;
$session_file_name = null;
foreach (glob('/home/session_folder/*') as $file) {
$content = file_get_contents("/home/session_folder/".$file);
if (strpos($content, $string) !== false) {
$session_file_name = "/home/session_folder/".$file;
}
}
Once found, you can then delete that session on the server.
if(file_exist($session_file_name)){
unlink($session_file_name);
}
BUT:
With many sessions this will be very slow and inefficient.
How you Should be doing it
Each page load you should be checking the logged in user is authenticated. Assuming your user details are database driven, every page load you should be checking that the details are genuine.
<?php
session_start();
if($_SESSON['user_id'] > 0){
/////
$sql = "SELECT banned FROM users WHERE user_id = :user_id";
/////
// Etc. etc.
$result = get MySQL result;
if($result['banned'] === 'Y'){
/***
* Member is banned. kick them out.
***/
$_SESSION = []; // reset session.
header("Location: index.php");
die();
}
}
UPDATE
If you are using the session ID as an identifier and you know the session id without needing to search for it; simply do this:
FUNCTION back_to_home() {
mysqli_close($db);
// save current admin session (optional).
$admin_session = session_id();
// get target id.
$session_id_to_destroy = $_SESSION['visit_user-session_id'];
// close the current session.
session_write_close();
// load the specified target session
session_id($session_id_to_destroy);
// start the target session.
session_start();
// clean all session data in target session.
$_SESSION = [];
// save and close that session.
session_write_close();
// Optional if you need to resume admin session:
// reload admin session id
session_id($admin_session);
// restart admin session. . ..
session_start();
// ...
// header should go to a specific file.
header('Location: ../index.php');
exit;
}
Related
I have this in my $_SESSION setting script:
<?php
//----------------------// Start session----------------------
if(!isset($_SESSION))
{
session_start();
}
//------------------------------------------------------------
//------------------// Check if Username $_SESSION is set------------------------------------------
if (!$_SESSION['Username']) { // If not current User
header("Location: ./logout.php"); // Session destroy file that leads to session logout landing page
exit();
}
//------------------------------------------------------------
?>
Now, what I basically do is just check if Username SESSION is set. But, I have come to notice something strange while putting another user through:
If we click the same link at the same time and arrive on the landing page same time, I noticed I can see my Username displayed as his Username and his personal data like email and phone replaced mine in my very own PC! This is really strange to me as we do not even live in the same country or even share same PC.
So, it is obvious I have not secured my SESSION and I have used a lame approach without thinking about security and this can be abused with SESSIONS hijacked.
How do I resolve this conflict? How do I restrict each logged in user to a particular session without conflicts if two or more users access the same resource at the very same time? I need help. I can't sleep since I found this.
After reading your responses, I will now show a snippet of the functions.php file which outputs Use data from DB.
First, I get the UserName value from session using:
$UserName = $_SESSION['Username'];
With this value, I query DB to get more user details:
//------------Get User Info -- All user column
$Get_User_Info = mysqli_query($conn,"SELECT * FROM customers WHERE User='$UserName'");
/************************************************************/
/************************************************************/
$Get_User_Info_row = mysqli_fetch_array($Get_User_Info,MYSQLI_ASSOC);
/************************************************************/
//---- Now list all user rows
$GLOBALS['Skype'] = $Get_User_Info_row['Skype'];
$GLOBALS['Jabber'] = $Get_User_Info_row['Jabber'];
$GLOBALS['ICQ'] = $Get_User_Info_row['ICQ'];
$GLOBALS['Join_Date'] = $Get_User_Info_row['Join_Date'];
$GLOBALS['Join_Date_Time'] = $Get_User_Info_row['Join_Date_Time'];
$GLOBALS['Balance'] = number_format($Get_User_Info_row['Balance'],2);
The above is what is contained in the functions.php which I require with each page I need protected.
As you can see, I barely see where I have done too much wrong there.
I have 2 websites. Now I want to login a user on my second website only if my first website has a logged in session.
For Example:
$checkSiteLogin = //check if my first website has a logged in user and return the $_SESSION['id'] or false if not.
if(!$checkSiteLogin)
$_SESSION['id'] = $checkSiteLogin
I don't know if it's really what you want but as you show in your example, you want to check if your user has already or not a login session opened in your first site. Then, with the result of your test, login the user on your second website.
First, to check if there is already a session, you need to use the function isset to ensure that there is an existing id session like this :
if(isset($_SESSION['id'])) {
//There is an existing id session so log the user on your second website
} else {
//Create a new session id
$_SESSION['id'] = //id session
}
Remember, when you use session supervariables, you have to put at the beginning of your scrip, the command session_start();
Hope it will help you partially.
Good luck !
So I got an ini.php file which I included on top of every file. It includes my database connection + session_start().
When the login of the user is succesful then I set a session which equals $_SESSION['login'] = true.
Now I can do stuff like this:
if (!isset($_SESSION['login'])) {
include 'php/includes/login_form.php';
}
else {
include 'php/includes/welcome.php';
}
What if I wanted this specific login to be specific to the user? Do I have to link the session somehow with the username on login?
A session is always unique to one visitor. session_start generates a random session id, which it puts in a cookie, which only your current visitor will receive. On the next request, that cookie with the unique session id is picked up on by session_start and the session is resumed.
However, this by itself won't tell you which of your user accounts specifically the session belongs to. You'll have to record that information yourself. E.g.:
if (/* login successful */) {
session_start();
$_SESSION['user_id'] = $loggedInUserId;
}
Here's my code:
if (!isset($_SESSION)) {
mysql_select_db($database_localhost, $localhost);
$log = mysql_query("SELECT email FROM loggedin") or die(mysql_error());
while($cols = mysql_fetch_array($log)){
$value = $cols['email'];
$email[$index] = $value;
$index++;
}
session_start();
$user=session_id();
}
It was working before. But right now, when I have someone log into a user from a different computer and then I log in, it does not give the second user a session id.
If I were to take the if(isset) conditional out, it would then create a new session along with new session id but that same id would then be applied to the first user that logged in.
Why is this happening, and how do I make it so that each logged in user has a seperate session id.
Each session has its own, unique session id. You should not care about the value of the session id, other than know that session_start() uses it to find the previous session. Your code does not do anything useful, but a proper way of handling users logging in would be something like the following, in psesudo-ish code.
session_start();
if (isset($_POST['email'], $_POST['password']))
{
$user = fetch_user_from_database($_POST['email']);
if (!$user)
{
// display error about user not found (or wrong password)
}
else if (!password_verify($_POST['password'], $user['password_hashed']))
{
// display error about incorrect password
}
else
{
$_SESSION['user_id'] = $user['id'];
}
}
When you want to check if someone is logged in, do !empty($_SESSION['user_id']), when logging someone out use session_destroy and session_regenerate_id. Either fetch the user information on each request from the database, or store the complete user row / object in the session, depending on which tradeoffs (an extra DB lookup vs handling stale data / larger session object) you want to live with (unless you're doing high traffic sites, just do whatever). If you go with storing the whole user in the session object, unset the password hash or other sensitive information before doing that.
Since you want to track users across multiple sessions, you have to have some way of identifying them when creating the session, and an email/username/password combination is the usual way to do that.
Are you sure there are no other session_starts in your codebase?
Not really sure what your code does, but would this work out for you?
session_start();
if (!isset($_SESSION['user'])) {
mysql_select_db($database_localhost, $localhost);
$log = mysql_query("SELECT email FROM loggedin") or die(mysql_error());
while($cols = mysql_fetch_array($log)){
$value = $cols['email'];
$email[$index] = $value;
$index++;
}
$user = session_id();
$_SESSION['user'] = true;
}
You can add uniqid() to the session id .
i have this code:
$username = $_POST["username"];
$password = $_POST["password"];
if(mysql_num_rows($result80)>0)
{
$row80 = mysql_fetch_assoc($result80);
$_SESSION["loginmng"] = 1;
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
$fname = $row80["fname"];
$lname = $row80["lname"];
$userid = $row80["id"];
}
and every thing is ok because i tryed to echo the session and its work in the same page (index.php)
now i have this check:
if(($_SESSION["loginmng"]!=1)||(!isset($_SESSION["username"]))||(!isset($_SESSION["password"])))
{
header("Location: index.php");
}
when i put this into new folder:
newfolder/index.php
the check is not working right,when i have logged in , and the session is set....when i am tring to echo $_SESSION["loginmng"] and the other sessions,,its values is empty like no session setted and the header is got run ...and go to index...i have put session_start(); in the first php line too
i tryed too:
if($_SESSION["loginmng"]!=1)
{
header("Location: ../index.php");
}
and the same thing...like no session set, what may be the problem
A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.
PHP Session Variables
When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.
Starting a PHP Session
Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the <html> tag.
Maybe you forgot to add session_start(); on top of the file.
To make session start on each page you need to start the session on each page.
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.