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();
Related
I am trying to protect some php pages with roles. The code i am using its working when the people make the login but if they know the link and don't make the login they can access the page and i can't understand why.
Can anyone help me?
I am using this code to protect the page where only users with role "admin" can access.
<?php
// Initialize the session
session_start();
// If session variable is not set it will redirect to login page
if(isset($_SESSION['username'])){if ($_SESSION['role']=='admin') {
} else {
header('location: index.php');
}
}
?>
Try this:
<?php
// Initialize the session
if(!isset($_SESSION)) {
session_start();
}
// If session variable is not set it will redirect to login page
if(empty($_SESSION['username'])) {
header('Location: index.php');
} else {
if ($_SESSION['role'] != 'admin') {
header('Location: index.php');
}
}
?>
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'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';
}
?>
I am looking to placing all code above in header.php which I include.
The first few lines of header has :
<?php session_start();
if(!isset($_SESSION["loggedin"])){
header("Location: login.php");
exit;}
?>
The unfortunate consequence of this is that when the user gets redirected to login.php they hit a redirect loop.
Would the best way forward to be creating an If statement along the lines of pseudo:
if (page="login.php")
{
//do not redirect to login.php
}
Before the session_start();?
You can wrap the code
if(!isset($_SESSION["loggedin"])){
header("Location: login.php");
exit;}
In a function such as:
function ensureLoggedIn()
{
if (!isset($_SESSION["loggedin"]))
{
header("Location: login.php");
exit;
}
}
Then you call this function from all the pages where authentication is required.
Such as calling this function on secretpage.php will redirect to login.php if the user is not logged in.
Login.php should not have this function.
Before includeing header in login.php, do something like this:
$logging_in = true;
Then, modify header
if(!isset($_SESSION["loggedin"])){
to
if(!isset($_SESSION["loggedin"]) && !isset($logging_in))
In your login page you can check if the user is already logged in and redirect them to proper page.
<?php
if( userIsLoggedIn ){
//redirect to main page page or logout them forcefully
}
?>
//your login form can go here