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().
Related
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 have the following PHP code:
if(!isset($_SESSION)) {
session_destroy();
header('Location: register.php'); //redirect to the orginal form
} else {
$businessOwnerID = $_SESSION['business_owner_id']; //The Business owner ID
$mobileValidation = $_SESSION['mobile_validation'];
}
I am not unserstanding why it isn't redirecting to register.php
I tried destroying all sessions by doing session_destroy(); but it did not work either
Since you obviously don't really want to just check if there is a session (there pretty much always will be) but if particular session attributes are set, you should be doing it this way:
if(!isset($_SESSION['business_owner_id'], $_SESSION['mobile_validation']))
{
session_destroy();
header('Location: register.php'); //redirect to the original form
}
...
The $_SESSION super global will always be set after calling session_start().
Instead, you should check if a particular value is set:
if(!isset($_SESSION['business_owner_id'])) {
session_destroy();
header('Location: register.php'); //redirect to the orginal form
} else {
$businessOwnerID = $_SESSION['business_owner_id']; //The Business owner ID
$mobileValidation = $_SESSION['mobile_validation'];
}
I have a login page and I want to achieve this effect:
If user fails to login, display error message. After user presses refresh button, the error message should not be visible anymore.
I dont want to pass $_GET variable, for example index?page=login$failure. I want to do this in invisible in url way.
<?php
if(isset($_POST['submit_form_register'])) {
...
if($login === false) {
$user->go_to('index.php?page=login'); //Redirects back, cleaning the $_POST data.
}
..
}
?>
Now how do I say for my form, that something before redirect went bad without addint it with $_GET?
Update. So using sessions, can I do like this?
<?php
if(isset($_POST['submit_form_register'])) {
...
if($login === false) {
$_SESSION['is_form_error'] = true;
$user->go_to('index.php?page=login'); //Redirects back, cleaning the $_POST data.
}
..
}
?>
And for HTML output:
<?php if(isset($_SESSION['is_form_error']) and ($_SESSION['is_form_error'] === true)) { ?>
<div>Your email or credential is invalid.</div>
<?php } unset($_SESSION['is_form_error']); ?>
But this one doesnt work for me. I bet its because something wrong with unset. Any tips?
SOLVED: Didn't have exit; after header(); in $user->go_to($url);
You could use Session for show and hide errors
When user enter wrong user/pass you set error session and use it in view and then delete session(after showed)
`//Set Session
if (!$success) {
$_SESSION['login_error'] = 1;
}
//show
if (isset($_SESSION['login_error'])) {
echo "Invalid Username/Password";
unset($_SESSION['login_error']);
}`
Don't forget to start code with session_start();
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
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.