Checking if a site is set to sessions - php

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 !

Related

Destroy the Session from a other user

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;
}

Session for every user unique or do I have to set it myself? If so how?

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;
}

How Check current PHP session set or unset

Guys in my php project i want to check on Login page session's status..if its unset i want user to login.
ihave added this code to login page but it doesn't help as it loops.
if (strlen(session_id()) < 1) {
?>
<script>window.location.href="login.php";</script>
<?php
}
elseif(strlen(session_id()) > 1){
?>
<script>window.location.href="index.php";</script>
<?php
}
Now other thing I want is if session is already started and if user manually tries to go on login page from address bar he should be redirected back to that current page.
If he is not logged in he should be redirected back to login page if he tries to open directly any page.
Also a new doubt with this is
Guys i m using wamp server to run my PHP projects.I have used PHP sessions in my projects,Now when a user logins from one project the sessions get set and if on same pc if user open some other project which are not linked to each other he gets directly logged in without even doing it, if he logouts from one project he gets logout from all other project running on that pc.
Try this:
<?php
session_start();
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == 1) {
//session is set
header('Location: /index.php');
} else if(!isset($_SESSION['logged_in']) || (isset($_SESION['logged_in']) && $_SESSION['logged_in'] == 0)){
//session is not set
header('Location: /login.php');
}
?>
In reply to above comments, yes you should create a session variable when the user is logged in. Edited code to reflect it.
you want to be checking for a particular session value, not the existence of a session ..
if ($_SESSION['logged_in']==1){
//
}else{
//
}
set $_SESSION['logged_in'] to 1 on log in and unset it (or set it to 0) on logout
Remember to include session_start(); on the top of every page to get the values of variable SET in the SESSION through $_SESSION['example'], otherwise You will not be able to the session Variable values ,
OR
A different Approach is to use session_start(); inside config.php file and include that file on the top of the code of every page where sessions are required otherwise U will not be able to get the value of SESSION variable..!!

Check whether user is logged in or not

I am doing a web-application using PHP for job searching.
I have one query; when user is not logged in and wants to apply for the job given by clicking 'apply' button, he redirects to the login page. If the user is logged in when clicking, he should get directly to the application page. I'm not sure how to implement this.
I'm confused because I'm new to PHP.
Your question is very vague - maybe start with Authentication in PHP
Well, when the user clicks on 'apply' in your application the user is redirected to the login page if he is not logged in(which you can check if user session exists or not), remember when you redirect the page send the url of the current page in parameters to your login page so that when the user logs in he can be redirected back to the previous page and click on apply for that particular job.....
This is how the logic works, if you want the php, mysql explanation it would take some time for you to understand as you yourself conceded you are new to php..
You could store a value in the Session called "Login" and set this when the user logs in. This can also be used to re-direct the user if they haven't been logged in:
<?php
// check that the session variable does exist
// check that the user 'LoggedIn' has been set to 1 (true)
if (!isset($_SESSION['LoggedIn']) && $_SESSION['LoggedIn'] != 1)
{
// redirect to login page for user to authenticate themselves.
// pass page location (with parameters if necessary) to redirect
// the user on successful login.
header("Location: Login.php?redir=ApplyForJob.php?JobID=12345");
}
else
{
// user is logged in
// redirect the user directly to the apply for job page.
header("Location: ApplyForJob.php?JobID=12345");
}
?>
Can you, when the user logs in, assigns a $_Session variable to that user? i.e., after authentication, you set the $_SESSION['user'] variable.
$_SESSION['user']='admin';
So if you want to check whether the user is already log in after that, just use this:
if(isset($_SESSION['user']))
{
// user is login, direct to the job page
}
else
{
// no login, go to the login page
}
On each page set a cookie or session to which page they were just on:
$expire=time()+60*60*24*30;
setcookie("wherewasi","",time() - 1000);
setcookie("wherewasi",$_SERVER['REQUEST_URI'], $expire);
Then after login redirect them:
$loc = ($_COOKIE['wherewasi'])?$_COOKIE['wherewasi']:'index.php';
header("location: ".$loc);
exit();
There are two things that you need to worry about... checking that they've logged in, and then once they've logged in, directing them to the correct page.
This is all about 'saving state' across page requests. To do this you need can use cookies or more usefully sessions (which may be done via cookies or handled by the PHP engine for you automatically).
Sessions are probably a good way to go. To use sessions, every page needs to start with a
<?php session_start(); ?>
at the very least, before any html code that writes to the browser.
Once that's done you can use your the session variable to store
<?php $_SESSION['user']='joe_blow'; ?>
(and check)
<?php
if(isset($_SESSION['user']) && $_SESSION['user']!='' {
// do something
}
?>
whether the user is logged in, and which page they need to be redirected to after login.
<?php header("location: ".$_SESSION['redirect_location']));
But in order to write the any more useful code I think people would need to know what authentication method you were using... (How are you doing your login? Are you storing ID's in a database? Are you using an off-the-shelf package?)

Are there any session security loopholes in my PHP script?

After I authenticate user login info, i create this session for them:
$_SESSION['username']= $userName;
Then, I redirect them like this:
header('Location:www.domain.com/profile/' . $_SESSION['username'];
I want my website to have a beauty URL, something like: www.domain.com/profile/userName
Thus, in all my redirect links (HTML <a> tag or PHP header() function), I will use:
"www.domain.com/album/" . $_SESSION['username'];
Are there any security loopholes?
Edit:
Do I need to create session id first using session_id()?
So, to check:
if(!isset($_SESSION['id']){
//redirect to login page
}
Normally while using Sessions we also need to be aware of -:
Session Hijacking , Session Fixation
I suggest in your code after user logged in store the username in session variable also store one more unique value such as USER AGENT in a session variable. so that every page the user visit we can check for whether the same USER AGENT and SESSION ID exist this would make it much secure. To make it much more secure do the encryption like MD% on User AGENT so that hackers cant reproduce it.
Quoted from PHP SECURITY GUIDE
<?php
session_start();
if (isset($_SESSION['HTTP_USER_AGENT']))
{
if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
{
/* Prompt for password */
exit;
}
}
else
{
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
}
?>
Refer :
PHP Security Guide on Session
Another Thread on Session security
What are you protecting? What are you doing to verify that they have authorization? Are you protecting their profile and verifying that they have authorization because they have the session key? You don't ever mention checking that they have a session variable.
You won't even need to know the session ID. That is immaterial to storing whether the user has gotten authentication, that's just the mechanism which indicates what session information they should be using.
When the user logs in, you want to store something like
$_SESSION['authed_user'] = true;
And then, on subsequent attempts to edit information you do:
if ($_SESSION['authed_user']) {
// do something authed users can do
}
And naturally, you'll really probably want some sort of levels of authorization. I recommend you consider using something like SimpleAuth...
You need authorization on the page that allows user to edit their profile. If they'll be editing on the http://www.domain.com/profile/[username] page then you need to check if their $_SESSION['username'] is equal to the profile page they are on.
Otherwise anyone would be able to type in the URL (basically guess a profile number or name) and edit it.
But yes, you should first check if they've logged in AT ALL:
if (IsSet($_SESSION['username'])) {
// Logged in
} else {
// Not logged in
}

Categories