If isset $_SESSION goto this page? - php

Ok, having trouble here:
I created a login script, so after a person logs in then they will get direted to another page. And also, I have it redirecting them to the login page if they try and access one of those other pages.
My problem is, if a user is logged in and stumbles to the login page again --by accident-- I would like for it to recognize that the user is logged in and redirect them to that next page (which is index2.php) ?? Having troubles :-(
Here is my code so far:
require_once "inc/functions.class.php";
$quickprotect = new functions('inc/ini.php');
if (isset($_SESSION['goAfterLogin'])){
$goto = $_SESSION['goAfterLogin'];
unset($_SESSION['goAfterLogin']);
}
else $goto = $quickprotect->settings['DEFAULT_LOGIN_SUCCESS_PAGE'];
if (isset($_POST[username])) {
if($quickprotect->login($_POST[username], $_POST[password])) header ("Location: $goto");
}
Here is how I store a users session in the functions page
public function is_logged_in() {
//Determines if a user is logged in or not. Returns true or false;
if ($_SESSION['logged_in'] === md5($this->settings[ADMIN_PW])) {
return true;
}
else return false;
}

You don't mention how you store your users in your session, but something like this should do it for you:
if(isset($_SESSION['user']))
{
header("Location: index2.php");
exit;
}
This will check if you have a user in your session, and if so, redirect to index2.php.
You need to change 'user' according to your session key.

Related

PHP How to completely destroy a session after leave the page

I want to make a simple PHP page where you can only access if you log in first. My code is something like this:
if (the user logged in correctly) {
session_start();
echo "THE HTML PAGE. (I did this in echo because I only want to show it for the logged in users.)";
} else {
header ("Location: index.html");
die();
session_destroy();
}
So my goal is that, when the user click onto the "Go back on page" button, the session gets destroyed, and only start a new after logged in. But now, if the user click onto the "Go back on page" button, than click onto the "Go forward on page" button. it says, Document Exired. It's cool, but if I refresh the page, I can access the page without login.
Here is a solution
// put on top of every page
session_start();
function is_logged_in(): bool
{
if (isset($_SESSION['email']) && isset($_SESSION['id']) && isset($_SESSION['is_logged_in'])) {
return true;
} else {
return false;
}
}
function is_auth()
{
if (!is_logged_in()) {
session_destroy(); // change happend here
header("Location: index.html");
die();
}
}
is_auth();
// add your code here
if(isset($_SESSION['email']) && isset($_SESSION['id']))
{
return true;
}
else
{
return false;
}
// and then call this function in header file to check.
header ("Location: index.html");
die();
session_destroy();
Regarding session destruction, you cannot do it that way. See below:
First you need to destroy the session.
Then you need to redirect the user.
Correct:
session_destroy();
header ("Location: index.html");
die();
sometimes unset function also works see unset and destroy are two seprate function,
unset is useful for unsetting the some values like email,id,name etc and destroy completely destroys session, so make sure destroying the session you again not need the session so try to use unset().

How to redirect back to previous page after login in Code Igniter?

Okay, so this is what I do:
I go to www.mywebsite.com/orders?id=1
It redirects be to login before proceeding.
I log in successfully but it redirects to www.mywebsite.com/orders.
If I am already logged in and go directly using GET method, it works fine. But if I am asked to login, the GET method disappears.
How do I preserve ?id=1?
Before redirecting the user back to the login page store the current page (the requested page) in a session variable. Assuming you have a function called check_login this would more or less look like what you should do:
public function check_login() {
if (!$this->session->has_userdata('logged_in') || $this->session->logged_in !== true) {
if (!empty($_SERVER['QUERY_STRING'])) {
$uri = uri_string() . '?' . $_SERVER['QUERY_STRING'];
} else {
$uri = uri_string();
}
$this->session->set_userdata('redirect', $uri);
redirect('/auth/login');
}
}
Then when the user successfully logs in your login function should somewhere have the following logic:
public function login() {
// form validation
// get post vars
// check username/pwd against db
if ($login) {
if ($this->session->has_userdata('redirect')) {
redirect($this->session->redirect);
} else {
redirect('/dashboard');
}
} else {
// error logging in
}
}
session variable could store the id.While log in using session pass the id value.You can retrive the value anywhere in session.
$this->load->library('session');
$this->session->set_userdata('userId', 'YourId');
where userId would be the name of the session variable, and YourId would be the value.
Simply Use this
redirect($_SERVER['HTTP_REFERER']);

How to authenticate securely by session tokens and cookies? updated

I tried to write my own authentication method (school project), and I'm stuck.
Please advise, how to solve a secure authentication:
There is an index.php which contains everything that needs to be "protected". I will copy the relevant parts of my code here.
updated index.php
session_start();
function checkUserAuth(){
$authStatus = false;
if (isset($_SESSION['PHPSESSID'])){
if ($_SESSION['PHPSESSID'] == $_COOKIE['PHPSESSID']){
$authStatus = true;
}
}
return $authStatus;
}
if(!checkUserAuth()){
include_once(dirname(__DIR__).'/admin/authentication/login.php');
exit();
}
If the checkUserAuth() determines, that there is no properly authenticated user, will include the login.php and stop the rest of the script.
updated login.php:
if(array_key_exists($username, $users) && password_verify($password, $users[$username])){
$_SESSION['PHPSESSID'] = $_COOKIE['PHPSESSID'];
$_SESSION['login_user'] = $_POST['user'];
What I imagine that might happen, is that if the login details are correct, the login.php sets a cookie, and refreshes the page. Then the index.php will detect the cookie, and skip the login part.
The login is pretty much figured out, and thanks to Juned, I think it is working now. However I don't know how secure is this?
On a scale from 1 to very, how wrong I am?
There are loads of ways of doing this. The below pseudocode is not the most efficient but should work and I don't think what you've done above will actually work.
Does this help?
login.php pseudocode
<?php
session_start(); // this function checks if there's a session ID already set, if not, sets one.
if(array_key_exists($username, $users) && password_verify($password, $users[$username])){
// do your login details checking here
// if login details correct
// set a flag in the $_SESSION superglobal and whatever else you want to store about the user like their username e.g.
$_SESSION["loggedIn"] = true;
$_SESSION["username"] = "$_POST['user']"; // better practice to fetch a clean version from your database
//else return user to login page
}
?>
index.php pseudocode
<?php
session_start(); // this will fetch the session ID and other variables that you might have set e.g. username, logged in status
function checkUserAuth(){
$authStatus = false;
if (isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] === true){
$authStatus = true;
}
return $authStatus;
}
if(!checkUserAuth()){
// redirect to login page. e.g.
header('Location: login.php');
exit;
}
?>

Logged but can't access page for logged users?

I'm pretty noob in PHP but I'm trying to exercise. Since yesterday I'm on a problem I can't even understand, I thought my code was correct but it seems wrong
So here is my function to allow pages for logged users only
functions.php
function logged_only()
{
if(session_status() == PHP_SESSION_NONE)
{
session_start();
}
if(!isset($_SESSION['auth']))
{
$_SESSION['flash']['danger'] = "You can't enter this page - not logged in";
header('Location: login/login.php');
exit();
}
}
So It's supposed to redirect me to login page if I'm not logged-in, simple
login.php
elseif(password_verify($_POST['password'], $user->password)){
$_SESSION['auth'] = $user;
$_SESSION['flash']['success'] = 'You're now connected';
header('Location: ../profile.php'); // user's homepage
exit();
There is some code above and under this, but it works pretty good.
So in this case the script should insert user's informations into his $_SESSION but it does nothing but redirect me at login.php. Also, the "profile.php" only contains "logged_only();" and a print_r (when I delete the redirection to login.php) of the $_SESSION, which shows nothing but "You can't access this page" (as I'm sending a message via $_SESSION)
Someone to guide me ? Thanks
You maybe should read about the session_start() in PHP: PHP Manual
In short words: session_start() starts a new session or recovers the already existing session with the client.
So after each redirect (also to your login.php) you need to call session_start().
There is no need for
if (session_status() == PHP_SESSION_NONE){
session_start();
}
You should only use
session_start();
(In both, your functions.php and your login.php) before accessing the $_SESSION variable.
functions.php
function logged_only(){
session_start();
if(!isset($_SESSION['auth'])){
$_SESSION['flash']['danger'] = "You can't enter this page - not logged in";
header('Location: login/login.php');
exit();
}
}
login.php
session_start();
// ... Rest of code
elseif(password_verify($_POST['password'], $user->password)){
$_SESSION['auth'] = $user;
$_SESSION['flash']['success'] = 'You're now connected';
header('Location: ../profile.php'); // user's homepage
exit();

Make php session active OR if logout return to previous page

Using the following php script. How I make active the session till the user logout. Its logging out every 30 min(approximately). OR if logout user redirect to the last page visted.
<?PHP
require_once("./include/membersite_config.php");
if(!$fgmembersite->CheckLogin())
{ $loggedin="0";} else { $loggedin="1"; }
if ($loggedin=="1") {echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('You are already signed in. Please continue to use')
window.history.back();
</SCRIPT>");
exit; }
if(isset($_POST['submitted']))
{
if($fgmembersite->Login())
{
$fgmembersite->RedirectToURL("Upload.php");
}
}
?>
function CheckLogin()
{
session_start();
$sessionvar = $this->GetLoginSessionVar();
if(empty($_SESSION[$sessionvar]))
{
return false;
}
return true;
}
That's a PHP config issue. If you don´t have any access to the php.ini file or don´t wanna mess with it, what you can do is that every time you enter a page you save the current page in a table on the database (it should have a relation with the user table), and when the user log outs after the 30min limit, you just retrieve that value from the database.
You can get the current URL with $_SERVER['PHP_SELF']. To check if the user logout just save a session variable and everytime the page is load do:
if(!isset($_SESSION['userid'])){
// redirect to the page in the database table
header("Location: ".$field_from_db);
}
Hope it helps!

Categories