I am new in PHP and facing a problem with security.
I use this to redirect unauthorized users if they not logged in.
<?php
session_start();
if(!isset($_SESSION['user_id'])) {
header('Location: login.php');
}
?>
It is on every top of my page but when I log in and click my protected page it will redirect to login page instead of original/protected page open and my session variable is set on my login page how to include this session variable in my protected page from login page.
If when, you log in, it sends you to login page, then $_SESSION['user_id'] may not be set, or you aren't including session in your file, to check it, do:
var_dump($_SESSION['user_id'])
on the page, and temporally leave out the header if the var_dump returns NULL, it means, $_SESSION['user_id'] is not set
Try this:
if(!isset($_SESSION['user_id']))
{
// The user id variable is not set. Therefore, the user is most likely a guest.
$_SESSION['user_id'] == 0;
}
if($_SESSION['user_id'] == 0)
{
// The user does not have a user id set. We assume, therefore, that they are a guest.
header("Location: login.php");
}
Also, in your login script, ensure that you are setting $_SESSION['user_id'] to anything other than 0.
Related
Let's say I have a page called, "user.php".
I want logged in users to only be able to access
user.php?user=username.
If someone types in user.php in their browser, I do not want them to see the general page that shows user.php without the url extension. Any tips? Thanks
When user logs in you should store a user in the session.
And on the page 'user.php' you can have a function if the user exists in the session
then let him in, if it doesn't exist just redirect him.
Set session once user logs in
$_SESSION['logged'] = 'YouCanPutUsersNameHere';
Use this function on every page you want your user to be logged in.
function checkLogin() {
if (!isset($_SESSION['logged'])) {
header("location: /login");
exit;
}
}
you can achieve this by using $_SESSION
after the user login add
$_SESSION['logedin'] = '1';
and at the top of the user page add
if ( $_SESSION['logedin'] !== '1' ) {
echo "Please Login to continue";
die();
}
also don't forget to start or resume session on both login page and user page
session_start()
Logout.php script:
session_start();
session_destroy();
session_start();
unset($_SESSION['admin_uname']);
session_regenerate_id();
$_SESSION['success_msg'] = "<strong>You've been logged out.</strong>";
header('location: //domain.com/admin/login');
exit;
Login.php (part):
if (isset($_SESSION['admin_uname']) && !empty($_SESSION['admin_uname'])) {
goPage("//domain.com/admin/dashboard"); // goPage is a selfmade PHP function that checks whether value is self, home or an url and redirects the user to the correct location
exit;
}
Core.php // the core is above all the content on every page. The script below checks whether the user is on a protected page, these pages are defined in the $protectedpages array.
if (isset($_SESSION['admin_uname']) && !empty($_SESSION['admin_uname'])) {
$admin_uname = $_SESSION['admin_uname'];
} else {
$protectedpages = array("contact", "offertes");
$currentpage = str_replace(".php", "", basename($_SERVER['PHP_SELF']));
if (in_array($currentpage, $protectedpages)) {
$_SESSION['error_msg'] = 'Your session either expired or you are not logged in. Please try again.';
header('location: //domain.com/admin/login');
exit;
}
}
When the user is logging out by going to the logout.php page. closes the browser, reopens the browser, goes back to login.php the if (isset($_SESSION['admin_uname']) part of the code on the login.php page is being executed, the user will pass by the core.php and return back to the login.php page with the message Your session either expired or you are not logged in. Please try again. because the core.php doesn't detect the user to be logged in or at least it doesn't detect $_SESSION['admin_uname'] is set or not empty. Normally you would expect this kind of behavior to trigger an infinite loop but it doesn't do that.
I hope it all makes sense and I narrowed it down to the code above. There is no other part of the script that can set the $_SESSION['admin_uname'] variable.
I have multiple pages that needs to be protected depending on the user privilege. I have a php to check the current session variable upon page load.
page being tested; the php code is placed above the !DOCTYPE. this code is suppose to check for unlogged in customers. if not logged in or no session variable set redirect to error page otherwise do nothing and load page normally
<?php
if (!isset($_SESSION["username"])){
header("location: error.php");
}
?>
my session variables are only set after logging in, after logging in the user is redirected to the page referred to above:
if (mysqli_num_rows($results6) < 1) { //$results6 is a query to check if the user exits in the users database
$logInMsg = "invalid log in";
} else {
session_start();
$_SESSION["username"] = $uName; //$uName is a user input user name
header("location: pageabove.php");
}
the problem is that even after logging in I still get redirected to the error page
That would be because you haven't started the session yet. You need to specify a session start on each page that you intend to use sessions in (Read more about session_start()):
<?php
session_start(); // start session
// do check
if (!isset($_SESSION["username"])) {
header("location: error.php");
exit; // prevent further execution, should there be more code that follows
}
This is for everything. On your login page and all. Anywhere you want to harness the sessions, you need to start it, otherwise it's "lost in the wind".
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 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.