How to check if a user is logged in not using sessions - php

I've been looking through alot of posts about how to check if a user is logged in or not and most answers that I found where making use of sessions (thats how I understood it anyways:-p)
I included the following code in the php file and it kinda seems to work:
<?php
else if ($action =="aboutUs") {
// opens about us page either in secure or unsecured area depending on login
session_start();
if(isset($_SESSION['username']))
{
echo openHTMLsecurearea();
echo aboutUs();
echo closeHTML();
} else {
echo openHTML();
echo aboutUs();
echo closeHTML();
}
}
?>
Basically if the user is loged-in I want to show the secure area and if not, then it should open the "regular" site.
When I first open the browser (and have deleted my history) it works as it is supposed to (opening regular site when not loged in and then secure area when loged in). However, when I then logout again it should show me the regular site again but it doesn't. It still shows me the secure area page.
I think that's because the same session is still running and therefore the username is still set even though I loged off.
I'm pretty sure that there is a way around but I can't figure it out. The openHTML and openHTMLsecurearea set up is probably not the best solution but it's a little too late to change this now so it would be great if someone could help me with a way around this to ensure the user is actually logged in or not.
Any help is really appreciated thank you very much.

First consider using session_start() before any single char outside <?php ?>
Logout code is simply <?php session_destroy ?> and have the same rule as session_start: no html before.
And as everybody tells you... No session, no login system - or really secureless

Related

How to require a user to be logged in

I'm fairly new to PHP an was wondering how I have to make the user login before they can go to any other page on the website.
For example on www.cyka.us/p/index.php it will redirect them to www.cyka.us/p/login.php
Have you ever used sessions in php? You can use sessions as a marker if a certain user is logged in or not. It can be implemented like this:
$isLogIn = $session('login');
if($isLogIn){
//go to other webpages
}
Search sessions for further information :)
You simply test for it:
if (!user_is_logged_in()) {
http_response_code(403);
include("p/login.php");
exit;
}
… the specifics of the user_is_logged_in function will depend on how you've implemented your login system.
You can do this with sessions concept in php. For every page you need check whether the user is logged in or not and redirect to (login)desired page.

PHP ending sessions(different ways) i dont understand

I'm trying to understand sessions and how some of the functions to end them work.
I've gone to different sites/and even here on SO and, well essentially, nothing is working.
I have an app I'm trying to work on and when the user logs in, I store the username like so
(not going to paste the whole code but you get the idea)
if($row == 1){
session_start();
$_SESSION['usrname'] = $login_usrname;
$_SESSION['usrpass'] = $login_usrpass;
header("Location:index.php");
exit;
}
On the index page of said app I have a check like so
session_start();
if(!isset($_SESSION['usrname']) && !isset($_SESSION['usrpass'])){
header("Location:login-acc.php");
exit;
}
And it lets them in. I check the cookies in firefoxes web dev tools and I see it being generated so I'm going to say "its working" so far.
Now when I want to log out, Long story short I have a logout link that takes them to a page that's supposed to clear all session data and redirect them to the login page. When I'm testing the app and I click the logout link, I get redirected to the login page but when i go back and click the "index page" link. it lets me right in.
In the logout file, trying to FORCE the issue in overkill lol, I have this and nothing seems to work.
unset($_SESSION['usrname']);
unset($_SESSION['usrpass']);
session_unset();
$_SESSION = array();
session_destroy();
setcookie('PHPSESSID', '', time()-3600,'/', '', 0, 0);
header("Location:login-acc.php");
exit;
It redirects me to the login page but again, when I manually go to index page it lets me right in. Or after being redirected to the login page, I hit the "back" button and lets me right in as well.
If I then go into FF Web developer tools app and delete all cookies etc, and navigate to the index page, then it locks me out.
As you can see above ive tried multiple things and in the end, I threw them all together which should do something. My question is since I've put in ALL those functions to try and delete/unset/remove in general the session, what else can I do? I'm a bit lost as to how its supposed to work.
Can someone steer me in the right direction?
You are missing a session_start() at the top of your logout page. It's trying to modify a session that doesn't exist!
You have to start a session in order to end a session. I recommend taking a look at...
http://php.about.com/od/advancedphp/ss/php_sessions_3.htm
// you have to open the session to be able to modify or remove it
session_start();
// to change a variable, just overwrite it
$_SESSION['size']='large';
//you can remove a single variable in the session
unset($_SESSION['shape']);
// or this would remove all the variables in the session, but not the session itself
session_unset();
// this would destroy the session variables
session_destroy();

PHP session managment, is this ok to do?

I have the following structure:
Index.php
Account.php
Login.php
CheckLogin.php
When someone logs in via login.php it checks the username and password and sets the following session variables
$_SESSION['username'] = $username;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
When they access Account.php
that includes the file CheckLogin.php which checks the HTTP_USER_AGENT and also if the username variable is set.
Now here's where I have the problem. If a user went back to index.php (home page) and is logged in I would like to display the account link.
However if the user is not logged in i.e. just visited the site I would like to show the sign up link.
I was thinking I could do the following:
<?php session_start()
if (!isset($_SESSION['username'])) {
// If username is not set destroy the session
session_destroy();
echo ("Sign up");
}
else {
// If username is set
echo ("Sign up");
}
?>
I know this is not fully secure however if someone managed to hijack the session and went to account.php it would do the check which should destroy the session and log them out if they are not legit.
Is this best practice or is there a better way to achieve this desired result. I can't help thinking everyone just visiting the site and creating and destroying sessions is a bad idea. Is it the right thing to do or is there anything else I need to take into consideration?
This is enough for checking. No need to destroy the session on every attempt.
<?php session_start()
if (isset($_SESSION['username'])) {
echo ("Sign up");
}
else {
// If username is not set
echo ("Sign up");
}
?>
If someone is able to hijack the session, he will also be able to access your account.php. As stated above, read a good tutorial on auth systems or use a plugin. Building an authentication without proper knowledge is a bit dangerous.
if your checking is only based on session sure your website will not be secured. and I have a couple of suggestions:
1- use CSRF for more security on every post you have.
2- session should be always encrypted and you should use a salt key with them.
this way you can secure more. and just for information sessions is not always the best way to secure your website.

PHP Sessions - Login Form - Unable to login

I have a simple script where a user logs in. I am trying to use sessions, so that a user remains logged in on whatever page he browses through the website.
I have these scripts:
index.php - http://pastebin.com/yqLtqPRC
login.php - http://pastebin.com/KcQWjfw1
dbConfig.php - http://pastebin.com/GKyfaJJV
upload.php - http://pastebin.com/iMrz3WB8
functions.php - http://pastebin.com/x44KrmxK
If the user logs in or is logged in, 'You are now logged in, $user' is supposed to be shown, but the default 'You are not logged in.' displays throughout the pages.
No error messages are shown whenever I change page or try to log in.
Latest version of the code can be found here: http://www.mediafire.com/?7n6qo3p4gpkaao4
Can anyone help please?
thanks.
Put the session_start() on the top of the page in each file where you need sessions just after<?php and you should be fine. You need to call this function before any actual html is echo'd on the page.
Read the php session documentation here
Further looking into your code, if you want to limit the user to see other pages only if he's logged in then make a new file called logincheck.php with contents below and include it on the top of each file by require_once("logincheck.php");. In this case don't put the session_start() code again as mentioned above.
<?php
session_start();
if(isset($_SESSION["username"])){
$welcomeMsg = "<p align='right'>Welcome, </p>" .$_SESSION["username"];
}else{
if(basename($_SERVER["PHP_SELF"])=="index.php")
$welcomeMsg = "You are not logged in";
else
header("Location:index.php");//will redirect the user to index page if he has not logged in
}
?>
Now u can use $welcomeMsg and echo it anywhere on page where u want to display the error msg.
Hope that helps answer your query.
form action="?op=login" method="POST" action="login.php"
why are using action twice in form?
action="login.php" is only required.
I didn't see exactly where your problem was, too much code to read, but by looking through 2 files (the first 2) I noticed some stuff that could become a problem:
A Session_id is supposed to identify a user. if you simply put in a boolean (true) I could easily break in your user reserved part of the site by just modifying my HTTP header.
second thing is that you put a redirect on the login.php before you echo something.... guess you wont see anything.... the redirect happens before the echo.
The third thing is that you should definetly hash the passwords you get and store. It is so sad when people get access to databases and have without any work all passwords of all people.
And a last advice: try to put the Session_Start as the first statement in every file... could be that.
I stopped at this point:
redirect('../TASK2PHP/upload.php');
what's that function and what does it do?
Maybe you meant to use http_redirect or header or HttpResponse::redirect ...
Here you go. There were a ton of errors.
http://www.2shared.com/file/A2V_Ztw8/login.html
That should at least get you started. It is also commented along the way. I did not use the functions.php file there was nothing important in there. Also when you use this change your dbConfig file accordingly.
I have edited index.php, login.php and setup working flow of sessions. Follow the code structure for setting up sessions in others file accordingly.
Download following login-form rar file;
https://www.box.com/s/1ie9ilp9jgluvokf6say
you code structure of login methods seems confusing and its always a good idea to echo everything before you redirect otherwise httpresponse complains about it. Moreover my advise is you first turn on error reporting its always a good idea to do development with error reporting enabled. You can do this inside your login.php just place at the beginning of the file.
error_reporting(E_ALL); or set E_ALL to 1
ini_set('display_errors','On');
TL,DR. But here is an article that teaches the general design pattern for this sort of thing. All web sites that use PHP client authentication follow this design.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html
You can copy and paste the code snippets from the article. If you have any questions about what the code is doing, please post a comment here and I'll try to help explain. ~Ray
Hope this may help :
you can debug if session is empty or not.
session_id() returns the string identifying the current session. If a session hasn't been initialized, it will return an empty string.
if(session_id() == '')
{
// session has NOT been started
session_start();
}
else
{
// session has been started
}
and
check session in php if empty
Make it on index.php file and include your pages if user logged in. and check inside each and every page you including. if user not set then redirect to login page.
example :
index.php
if(isset($_SESSION['UserId'])){
//make simple function to get the username from user ID
$dUserName = getUserName($_SESSION['UserId']);
echo "wellcome".$dUserName;
echo "<href='logout.php'>Logout</a>";
}
else{
echo "<href='login.php'>Logout</a>";
}
if(isset($_GET['page'])){
$includePage = "includes/".$_GET['page'].".php";
}
else{
$includePage = "includes/login.php";
}
if(isset($includePage)){
include($includePage);
}
sample page loading from index
sample.php
if(isset($_SESSION['user']) && $_SESSION['user'] != ''){
//show your page
}
else{
//redirect to login page
echo '<SCRIPT language="JavaScript">window.location="index.php?page=login";</SCRIPT>';
}
I have fixed the files...
The main problem is in login.php in the loginUser function.
Change this line:
$sql = "SELECT * FROM users WHERE Username = '$username' AND Password = '$password'";
To this:
$sql = "SELECT * FROM users WHERE Username = '".$username."' AND Password = '".$password."'";
The problem with the first line is that it is looking for the text '$username' (and '$password' and not the variable $username and $password
As you can see the solution is to close the string before and after the variables reference'
P.S. You would gain tremendously from using a framework such as CodeIgniter to build your site, besides for saving you a lot of time fixing errors like this, it is also much more secure.
Let me know if you need me to upload the fixed files.

PHP Session issues in Chrome

I have a web app I am developing for a school project, I am having issues with the logout page. When a user clicks logout it will send them to a logout.php which just looks like this:
<?php include ("includes/check_authorization.php");
// Unset the session and destroy it
session_unset();
session_destroy();
// Redirect to the home page
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=index.php">';
exit;
?>
It is very simple, but it will unset, then destroy the session, and redirect to the index, which is the login page. However when this is run the index immedietley redirects to a user homepage. The check_authorization page included at the top will redirect someone to login if the username and id are not set and matching in the $_SESSION, so this means that it is setting these for me? I am really confused as to how this is happening. I am using CAS for authentication.
EDIT: the check_authorization.php also initializes the session as well as checking those key values
For like this situation I did as follows, this is working for me all the browsers,
#session_unset();
$old_sessid = #session_id();
#session_regenerate_id();
$new_sessid = session_id();
#session_id($old_sessid);
#session_destroy();
Rather than just unsetting the data, try assigning a dummy value to the session, like:
$_SESSION['authKey'] = '!!INVALID!!';
session_unset();
session_destroy();
Even if the session 'revives', the authentication can't possibly succeed anymore because of the "fake" data.
There are some possibilities :
The most simple possibility : did you include the
session_start();
on top the file? before you include a file? I've been there before, and it pissed me off.
The second possibility : try to put
session_regenerate_id();
on the very top of your file (before you declare session_start();). Because in some Server Hosting, their configuration still using "LINUX" style that i can't explain to you here. But, the point is they always using "cache" when you redirect. In other words, you always redirect into your "cached" page when you rediret to another page. See.. it's hard to explain for you here. But just try the session_regenerate_id(); code, maybe it would work.
I never use the "echo" things in doing redirect things. Try :
header("location:index.php");
i don't know if this working or not. I just simply giving you my analysis based of my assumptions.
Hope these helpful. :)

Categories