What is the best way to check if a user is logged in and if its not make the page unreachable for him?
What does this code need to make it complete and safe:
if (isset($_SESSION['USER_ID']))
Kill the script
if (!isset($_SESSION['USER_ID']))
die();
Or print a friendly message, redirect to login page, or whatever you think is an appropriate response. Just kill the page before showing your premium content.
In Login page Add
$_SESSION['user_id'] = $user['id'];
In page which you want to make unreachable if not loggedin, Add at top
include ("auth.php");
auth.php
<?php
session_start();
if(!$_SESSION['user_id']){
header("location:index.php"); //page you want to redirect
}
?>
Now you can add auth.php in any page which you want to make unreachable if not logged in...
First of all you need -before any page output (even warnings and errors):
session_start();
So your code would be complete as follow:
session_start();
if (!isset($_SESSION['USER_ID'])) {
header ("Location: login.php");
die;
}
if USER_ID could not be blank it is better to check this too:
if (isset($_SESSION['USER_ID'] && $_SESSION['USER_ID'] != ''))
As a personal method for more complex login check: generate a random token when user did login and store it in database and put in an extra session. Then check if user_id session name and random session match together by a database check. This will prevent attacks by any type of fraud in session and cookies name.
Related
Basically, When a user signs up (register.php) succesfully..
I store all the data in database and direct them to step.php using
header("location: step.php");
Where they fill other different info which is then stored in the database.
So, a user must access the register.php page before accessing the step.php page.
How do I stop access to the step.php page by limiting its access to only those that just completed the register.php form.
PS - I am building a step by step registration process and is this even the best way out. Or what other ways can I do this?
On register page: define('VAR', true);
On top of step page: if (!defined('VAR')) header('location:index.php');
Use Sessions, set a session if the user did gone through register php (set it bevor you redirect the user).
If step.php is called, check for that session.
<?
//register.php Line 1
session_start();
//At the End
$_SESSION['doneRegister'] = true;
header("location: step.php");
?>
<?
//step.php Line 1
session_start();
if (!isset($_SESSION['doneRegister'])){
// Session not set
header("location: register.php");
}
?>
I've got a user login field that sets the session after they're validated on the login page:
$_SESSION['user'] = $user;
$_SESSION['id'] = $id;
And on this PHP page I only want logged in users to access I have at the top:
<?php session_start();
if (!isset($_SESSION['id']) && !isset($_SESSION['user']))
{
header('Location: http://--back to home page--');
exit(); <-- Added thanks to comments
}
?>
Is this enough to keep user who have not logged in off the page?
It's redirecting me back to the home page when I'm not logged in, but could people get around it?
Edit: I've added the exit(); now.
Users can bypass the HTTP Location header. Add a die(); (Which is equivalent to exit();) right after to prevent any other content from being sent to the browser.
if (!isset($_SESSION['id']) && !isset($_SESSION['user'])){
header('Location: http://--back to home page--');
die();
}
Other than that, note that a user can change the PHPSESSID cookie. If they find the id of an active session with the variables in question set, they will gain access to the page.
I've got a login page then I made a link to a page called logout and it contains this code:
logout.php
<?php
session_unset();
session_destroy();
header("Location:");
?>
Yet when I log out then hit the back button it takes me back. How do I change it so that it ask you to login again before showing you your previous page?
On the page you're going back to (or any page for that matter) you need to do checks to see if the user is logged in or not (i.e. has a valid session) and if not, redirect them to the login page.
Additionally, it might help for you to add some no-caching headers to this particular piece of code.
You have not set any location to redirect to.
Should be:
header("Location:http://example.com/login.php");
This way when you logout, it will redirect the browser to login.php.
EDIT:
Also, it would help to add a session validation condition to your main page.
Somenthing like:
if(!isset($_SESSION))
{
header("Location:http://example.com/login.php");
}
Before loading every page (or atleast, every PRIVATE/RESERVED page) you should check the $_SESSION variable to determine if the user is legally logged in or not.
If you don't perform this check, everybody would be able to visit every page of your website if they have the direct link to it. They may see a broken version of the page, but the access is granted nevertheless to not logged users.
<?php
session_start();
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(),'',0,'/');
session_regenerate_id(true);
?>
source: Manual
try this to check on each page if the user is logged in
if (!$_SESSION['logged_in']) { //you would have to make $_SESSION['logged_in'] when they login
header('location: login.php');
}
all this does is say if $_SESSION['logged_in'] is NOT set redirect them to the login page.
You would also need to other checks to make it secure.
I created a login page in php named as index.php. Now when the user logs in it redirects to mypage.php. The login works fine. But also mypage.php gets open when I type the url of mypage.php even without login. I want the user must logged in to see mypage.php and incase if he changes the url in browser then an error message should be triggered. What to do?
1.localhost/index.php
2.localhost/mypage.php
In index.php, once the user gets logged in successfully, set an session. like $_SESSION['login'] = true; before redirect. If invalid login, use $_SESSION['login'] = false; Don't forget to start the session on the top of the page. session_start();
In mypage.php, check if that session is set or not. If not set, throw error, else show the page.
session_start();
if(isset($_SESSION['login']) && $_SESSION['login'] == true) {
echo 'You are welcome';
} else {
echo 'redirecting to login page';
header('Location: index.php');
exit;
}
How are you storing the state of being 'logged in'?
You'll need to have your mypage.php check a variable that has been set by the index.php's successful login process.
Can you paste your code here and I can take a look
In order for a login to work correctly, your "secure" page (I use that term relatively because nothing is truly secure) needs to have some sort of validation conditional. In other words you need to have some way of determining if the user is logged in.
A simple way to do this in PHP is to set a session variable when you process the user's credentials. For example:
When the user successfully logs in set a session variable like so:
$_SESSION['isLoggedIn'] = true;
Then on the mypage.php check to see if the variable is set:
if(!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] != true) {
header("Location: index.php");
exit;
}
Please also note, it is imperative if you are using sessions that you have session_start(); as the first line of all of your files. This allows $_SESSION variables that were set on a separate page to be able to be read on the current page.
Hope this helps.
How can I prevent a user from accessing a page when they are not logged in? I want him to be redirected to the login page. I know it has something to do with sessions.
It works like this:
Start a session: session_start()
If Session["user"] == null, redirect to the login page, else continue.
In the login page, ask the user for password using a form
Post this form to the login page
Check against your authentication service (e.g. a table in mysql) if the user is authorized
If yes, Session["user"] = $userName, redirect the user to the page. If no, prompt for password again
Of course, this is all very, very simple. In your session, you could keep a complex user object, or anything. Good luck coding.
As Svetlozar Angelov pointed out the following code would work well:
if (!isset($_SESSION['nID']))
header("Location: login.php");
However.. this would not actually secure the page against users who really wanted access. You need to make some adjustments:
if (!isset($_SESSION['nID']))
{
header("Location: login.php");
die();
}
This prevents bots and savy users who know how to ignore browser headers from getting into the page and causing problems. It also allows the page to stop executing the rest of the page and to save resources.
Its also noteworthy that $_SESSION['nID'] can be swapped out for any other variable you are using to store usernames or id's.
When he logs - store a session variable. Then in the beginning of every page
session_start();
if (!isset($_SESSION['nID']))
header("Location: login.php");
If the login is ok
session_start();
$_SESSION['nID'] = 1; //example
Follow these steps:
Create a login.php page accessible to everybody where a user enters her username and password in a form. This form must be submitted to login.php itself. (action='login.php'). Also include a hidden variable in your form which tracks if the form has been submitted.
If the hidden variable is set, check if the username ($_POST['user']) exists in your DB, and that the password matches the username. If it does, store the username in a $_SESSION variable like this:
$_SESSION['username'] = $_POST['user'];
If it does not, reload login.php like this:
echo 'header("login.php")'; //You should not have echoed anything before this
Now include login.php in every user page you create. Suppose you were writing an email application, create an inbox.php like this
include ("login.php")
Now, login.php will check if the session variable 'user' is set and allow access to authorised users only.