When I login a new session is generated. How can I later know for which login the session was generated?
I am getting the session value, but how do I know which user the session is for and redirect him to that page?
You do not want to create a (new) session when the user is logging in. You create/resume the session on every page.
Here some example broken down to the essentials.
login.php
<?php
session_start();
if ($_POST['user'] == 'john' && $_POST['pwd'] == 'password') {
$_SESSION['loggedIn'] = true;
$_SESSION['firstname'] = 'John';
}
?>
admin.php
<?php
session_start();
if (!isset($_SESSION['loggedIn']) || !$_SESSION['loggedIn']) {
header('location: login.php');
exit();
}
echo 'Hello ' . $_SESSION['firstname'] . '!';
?>
A user visits admin.php
session_start() creates a new session. All data ($_SESSION) is stored on the server. A new cookie with the session's id is stored client-side.
The user is redirected to login.php in order there is no $_SESSION['loggedIn'] key set to true
session_start() revives the session by the cookie sent by the browser
The user submits a form and authenticates. Inside the $_SESSION array we note this.
User goes back to admin.php and can now access the page.
Related
I have designed a website and there is a logout option in sub menu.The code is in HTML and is here:-
<p>logout</p>
Now this successfully brings me back to the adminlogin.php page but after that whenever I press the back button present at the top of web browser I go to that page again where I was before pressing logout button. But this should not happen if I have pressed the logout button then there should be no way to go back to that page unless I login again
To avoid browser back button after logout:
You Have To Add the top of each page, to check if the user is logged
in. If not, they should be redirected to a login page:
Example:
<?php
if(!isset($_SESSION['username']) && !isset($_SESSION['useremail'])){
header("Location: login.php"); // redirect to login page or index page if email and username is not set in session
}
?>
Now on Logout page, Simply unset the username and useremail
session variable, and destroy the session or ( Cookies). what you set.
Example:
<?php
if(isset($_GET['logout'])) {
session_start();
session_destroy();
unset($_SESSION["username"]);
unset($_SESSION["useremail"]);
header('Location: index.php');
exit;
}
?>
Working CODE For All Pages After User Login: Home.php about.php contact.php etc..
Example:
<?php
// After User Login and come to home page.
require 'database_conn.php'; // Connection
session_start(); // Session start
?>
<?php
// If User is Not Login Then Redirect to `index` Page Automatically
//if(!isset($_SESSION['username']) && !isset($_SESSION['useremail']))
if(!isset($_SESSION['useremail'])){
header("Location: index.php");
// Redirect to index page if email is not set in session
}
?>
Working CODE For to Logout User: Logout.php
Example:
<?php
// After User Click On Logout page.
require 'database_conn.php'; // Connection
session_start(); // Session start
?>
<?php
if(isset($_POST['logout'])) {
if(isset($_SESSION['useremail'])){
unset($_SESSION["useremail"]);
session_destroy();
session_unset();
header('Location: index.php');
}
}
?>
Simple Logout Button
Logout
logout.php
<?php
if(isset($_GET['logout'])) {
session_start();
session_destroy();
header('Location: login.php');
exit;
}
?>
Or If Cookie Set Then
<?php
if(isset($_GET['logout'])) {
unset($_COOKIE['access_token']);
header('Location: login.php');
exit;
}
?>
You need session to do this.
So basically when you logged in you need to set session variable like
$_SESSION['loged_in']=1; // set session with desired name
And on logging out you need to destroy this session value
unset($_SESSION["loged_in"]); // unset specific session
or
session_destroy(); // destroy al
And most important part you need to check for this session value on each page where you don't want user to go with out log in. like
if(isset($_SESSION['loged_in']) && !empty($_SESSION['loged_in'])) {
redirect('login.php'); // redirect to log in page
}
So far, I have only the login.html files which has login form, redirects user once logged on and logout function. What I want to do is once a user logs in, they redirect to but their username is displayed on the top of the page. And with the file... I just want it to be able to logout the user. So far on my website, I can login as far as I am concerned, and it redirects once user logs in, but I can login as many times as I want, and I can logout as many times as I want.... It's complicated to sort out and I want to do this without SQL or any other server-side storage (since I am only using HTML local storage).
You have to remove the session of username in logout code
unset($_SESSION['username']);
Hope this helps..If not,It would be better if you could provide the code, so that the problem can be sorted out
WRITE THIS ALL IN TOP PAGE
IN YOUR LOGIN PAGE
<?php
session_start();
if (isset($_POST["submit"])) {
$username = $_POST["username"];
$_SESSION["username"] = $username;
header('Refresh: 5; URL=GameWebsite.php')
}
?>
IN YOUR LOGOUT PAGE
if(isset($_SESSION['username']))
{
session_start();
session_unset();
session_destroy();
//Then you may redirect to the login page if you want after sometime.
echo " You have successfully logged out... You will be redirected back to the login page in a moment. ";
header('Refresh: 5; URL=login.php');
}
else
{
header("Location:login.php"); // HERE WHEN USER NO HAVE SESSION
}
IN ANOTHER PAGES YOU CHECK
if(isset($_SESSION['username']))
{
}else
{
header("Location:login.php"); // HERE WHEN USER NO HAVE SESSION
}
in your login page write on top
if(isset($_SESSION['username']))
{
header('Refresh: 5; URL=GameWebsite.html')
}
In your logout.php write
if(isset($_SESSION['username']))
{
session_start();
session_unset();
session_destroy();
//Then you may redirect to the login page if you want after sometime.
echo " You have successfully logged out... You will be redirected back to the login page in a moment. ";
header('Refresh: 5; URL=Login.html');
}
else
{
header("Location: login.php");
}
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();
I've been having a really rough time trying to implement a logon system for my web application.
I have the basic logic working as far as my index.php goes - if users try to navigate there and are not logged in it redirects them to the logon screen. Once they've provided correct credentials they are directed properly back to the protected index.php page.
This logic in code is seen here:
(index.php)
<?php
session_start();
include_once 'db_functions.php';
require_once 'access.php';
if (!userIsLoggedIn()) {
include 'login.php';
exit();
}
The problem occurs when a user attempts to navigate to another protected page. My logic was for protected pages to check whether the user was logged in, and if not send them back to the index which would in turn send them to a logon screen.
(protectedpage.php)
<?php
session_start();
require_once 'access.php';
echo "Logged in: " + $_SESSION['loggedIn'];
echo "User: " + $_SESSION['email'];
echo "Password: " + $_SESSION['password'];
// receive data from HTML readcalllog request
$rName=$_POST["registration"]; //irrelevant post data
$rowId=$_POST["rowid"]; //irrelevant post data
if ($_SESSION['loggedIn'] == FALSE) {
header('Location: http://www.myapp.com/index.php'); //if not logged in, return to index.php, which in turn redirects to a logon page.
exit();
}
As you can see I included test echo statements to print out the details of the current session. When I would navigate to the page (turning off the redirect feature) to check the error messages it would print "000", without the "Logged in: " or "User: " text in front of it.
I performed a test and printed out the details successfully on the index.php page, so for some reason the session is being lost as I navigate from index.php to another protected page.
Any help would be greatly appreciated!
EDIT:
Here is a portion of the userIsLoggedIn() in access.php function which sets the session variables:
function userIsLoggedIn()
{
if (databaseContainsAuthor($_POST['email'], $password))
{
session_start();
$_SESSION['loggedIn'] = TRUE;
$_SESSION['email'] = $_POST['email'];
$_SESSION['password'] = $password;
return TRUE;
}
else
{
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
$GLOBALS['loginError'] =
'The specified email address or password was incorrect.';
return FALSE;
}
}
}
EDIT 2:
If I login to the index page, go to the protected page(which sends me to a logon screen) and login again, the sessions function properly and all protected pages are accessible.
I just need to figure out what's preventing the initial logon from creating a proper session that carries over.
First of all, you do not need to include session_start(); more then once in a page. Just insert it at the beginning of each file.
If I were you, I would use this statement to see if the user is logged in or not in the protected pages:
if ( !isset($_SESSION['email'] && !isset($_SESSION['password'] ) ) {
header('Location: http://www.myapp.com/index.php'); //if not logged in, return to index.php, which in turn redirects to a logon page.
exit();
} else {
echo "Logged in";
}
Also, I would recommend you using both $_SESSION and $_COOKIES to create a stronger log in system.
I currently have a login form that redirects the user to another page if the login is successful. The page is supposed to be a protected page that will not open for the user if they are not logged in and will redirect them to the login form page.
In order to do this I stored the login data (email & password) as session variables and used these to verify if the user is allowed to view the page.
In my login php page I have the following code
<?php
session_start();
if ($count == 1) {
$_SESSION['logged'] = 1;
$_SESSION['email'] = $myemail;
$_SESSION['password'] = $mypassword;
header("Location: account.html");
exit();
}
?>
And I begin my account html file with the following :
<?php
session_start();
if ($_SESSION['logged'] != 1) { //no session
header("Location:memberlogin.html");
exit();
}
?>
However any time I load the account page I am allowed to view it each time. Its my first time using the Session variableand Im not sure if i Used it correctly.
FIXED Thanks to suggestions below
I tweaked the code suggested below and my protected page is now working. Thanks for all the help.
The php code won't be referenced from an html page.
So, change account.html to account.php then add the session check code on top of the page as follows:
account.php:
<?php
if ($_SESSION ['logged'] !=1) {
//User is not logged in
header ("Location:memberlogin.html");
exit();
}
?>
However, redirecting is not the best solution, you can display an error message if user is not logged in, else grant user access to the page information.
You can implement it as follows:
account.php:
<?php
if ($_SESSION ['logged'] !=1) {
//User is not logged in, display an error message
echo 'You need to be logged in to access this page';
exit();
}
else{
//Display all information that only a logged in user can view
echo 'You are logged in, you can view the page';
}
?>