How to require a user to be logged in - php

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.

Related

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

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

prevent user from accessing previous (restricted) pages after signing out with PHP

When the user decides to sign out, they obviously do so by using a "Sign out" button.
When they do, this script is executed:
if(isset($_POST['submit_Logout'])){
$_SESSION['backend']->logout(); // see this function bellow
unset($_SESSION['user']); // unset only this session since there are other sessions I'd like to keep
session_regenerate_id(true); // makes sure the session id is updated, and the old one is discarded
KD::notice('success',$success_LoggedOut); // adding a notice to another session
KD::redirect('/'); // redirecting the user using header();
session_commit();
}
I'm just unsetting this particular session (user) since there's other sessions that keeps other data available, regardless if the user is logged in or not, to better the user experience.
The logout()-function looks like this - for now:
public function logout(){
$this->accessible=false; // just a flag to check against (see bellow)
$this->username=''; // empty the username
}
Since I'm unsetting the session that holds the related user data, I just realized that this function is probably unnecessary. Alternatively move the unset part etc. into the function..
Anyway, I've come to experience that when a user has logged out, he/she, or somebody else for that matter, has the opportunity to just hit the backwards button in their browser, and voila, they can view the page(s). Of course, if they start clicking on any links, they gets thrown out. But the back-button is still available..
I believe this happens as a result of cached pages/views by the browser. So when they click the back-button, they see a cached page/view stored in the browser memory or something..
Since this page, or view, is loaded into my template trough a index.php page with a permanent <head>, there's not much I can do about the caching of these restricted pages/views. Or is there?
Deleting records from the browsers history is not possible? or preventing these pages from being recorded in the first place?
Point is. What I need to do, i believe, is to force the browser to always request the page from the server. So regardless if the user hits the back-button, or a link to a restricted page, the page should always reqest it from the server, and not the browsers memory..
Or am I not getting this correct?
If so. I do wonder how. How is this usually done?
I have this in my class
private $accessible = false; // when logged in, this is set to true
public function accessible(){
return $this->accessible;
}
At the very top of the page that includes the views into the restricted area I have this:
if($_SESSION['user']->accessible()===true):
Othervise the user is prompted with a login screen.
But that doesn't work as expected. This check is not performed when the user uses the back-button in their browser...
Thanks in advance..
UPDATE
Heres a quick overview of my structure/layout:
/*
when the user is logged in/out, the script that does that is executed up here.
That includes setting the sessions etc. aswell - which means, if the user is not logged in, the access will be set to false.
*/
<head>
</head>
<body>
/*
Here I include different pages with php include;
These pages can be home.pg.php, contact.pg.php, and of course restricted.pg.php
each of these pages includes different content (views as I like to call them) that is presented to the user based on their interaction.
Now. When the user tries to access the restricted.pg.php, I have this at the top:
*/
if($_SESSION['user']->accessible()===true):
/* now each view that is included here should be not accessable if accessable() is not true. */
else:
/* the user is presented with a login form */
endif;
</body>
Did this help?
All the pages that require some to login should have something like this,
session_start();
if(!isset($_SESSION['user']){
//REDIRECT USER TO LOGIN PAGE
}
If its because of the browser caching issue that hitting back is taking you back to cached version of the page (even though user is logged out) then you should redirect the user twice (good practice).
what I mean is create a file called logout.php so when user clicks on logout button,it redirect the user to logout.php (that'll have the session unset code) and after that redirect user to login page.
so current page ----redirects to---> logout.php ----redirects to----> login.php
i think in every page you can just check whether a session is set or not. ex. Session::handlelogin('user')
then you can just make a function namely handlelogin in Session class
Class Session {
function handlelogin($user) {
if (!isset($user)) {
//redirect the user to your login page
}
}
}
Notice: just set this up in top of the page if your using MVC architecture then you can set it up in the Controller
Session::handlelogin('user')

PHP Authenticate user for each page of website

I'm developing a website, where in most of pages user need to log in to view pages of website. What is the best way to check if user is logged in or not, and if not redirect it to log-in page.
currently I'm using following code to do that.
if(!isset($_SESSION["username"])) //I set the session when user log in and destroy when user logout
header("location: login.php");
There are lot of pages and I put this code in every page. It also works well.
I want to know is there any other batter way to do this? Or what I'm doing is good way? and I don't need to change anything.
Simple Solution is create a file named as session.php
include your session checking code into that. Like,
if(!isset($_SESSION['YOUR_VAR'])) {
header('Location: login.php');
}
include this file into all your pages, with include OR require
I prefer require function. example in your home.php file at the beginning of page write,
<?php
session_start(); //don't forget to do this
require('session.php');
?>
NOTE : In future if you enhance your session checking code you just
have to change one file.
I usually just set a session like this once the user logs in:
$_SESSION['loggedIn'] = TRUE;
Then just check if TRUE or FALSE when needed.
ex:
if($_SESSION['loggedIn']){
//Something here
} else{
//Don't do it
}
It is depend on you architecture. If you are using any framework, like symfony you don't need to handle these for each and every page. I guess you are using pure PHP without any framework support. So you need to check whether the user is authenticated for each and every request by your own. I suggest you to without placing code segment related to logout in every page, just place it in a global function and call it in your every page. So that, if you want any simple change in that code segment, you can achieve it only changing that global function

Object Oriented php Session management

I have a webapp that uses login/logouts so I have session management. Basically every page so far starts with
session_start();
if(!isset($_SESSION['username'])) {header("Location: index.php");} else { rest of the page's functionality}
I am now creating a class (User.php); that will be accessed by another .php page. Do I need to implement the above for security, and if so how? Should I put classes above the webroot?
Thanks
first of all, although i assume you've thought of this; just to check if the username is set in a session is not particularly save. If you want to check if a user is logged in some additional tests should be present.
than back to your question; a page could possibly access the User class even if no logged in user exists (eg. when you want to display this particular users' public comments on a blog post). So no, your test would not be needed. Furthermore you could also build in a check if the user is logged in into the User class (or better still; the Authentication class you'll build around it), so you could do something like:
if(Authentication::is_logged_in($_SESSION['username']) === true) {
echo 'yeeehaaaa! You\'re logged in bro!';
} else {
echo 'what are you doing here?! Get lost! (or log in)';
}

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?)

Categories