PHP Infinite loop when user not logged in - php

I am having an infinite loop issue with this code. It's checking to see if there is a session variable, if there isn't, I want them to be redirected to the index page.
session_start();
if (! isset($_SESSION['foo'])) {
header('Location: /index.php');
}
exit;
I've tried putting the exit; and exit(); and endif; outside the if loop and inside, all are still giving me the issue of infinite loops. This code is located in the header page, which is then called on every page, so you can only access the index page if you are not logged in. That's the gist of why I want this code to exist in the first place.
Thank you for your help in advance.

Add something to your if statement that would exclude the index.php page. Something like
if(! isset($_SESSION['foo']) && strpos($_SERVER['REQUEST_URI'], 'index.php') === false) {
header('Location: /index.php');
}

If you make that check on the index page, it will redirect loop whenever a session is not set. You need to make sure this check is not made on index.php

I think you're just missing session_start();
page.php :
<?php
session_start(); // this is important
if (! isset($_SESSION['foo'])) {
header('Location: /index.php');
exit;
}
?>
index.php :
<?php
session_start(); // this is important
//stuff
$_SESSION['foo'] = 'stuff';
//other stuff
?>

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().

redirect to login index page if user not logged in?

I have multiple pages on my site, most of which are member only pages which a user should have access to only once logged in.
When a user lands at my page they automatically land on the index/home page (index.php). If a user tried to navigate to dashboard.php which is for members only, then they should be redirected back to index.php so they can log in.
at the top of all of my member pages like dashboard.php and manage_account.php i am including a header.php file like so:
include 'header.php';
once a user is logged in i create the session '$_session['user']'
And i am using the following header redirect to check if the session exists and if it doesn't then redirect that user.
<?php
session_start();
include 'config.php';
if (empty($_SESSION['user'])) {
header('Location: index.php');
exit;
}
?>
My problem is rather than cut and paste a header redirect code to each and every member page I just want to place it in the header.php page as this is being included in all of my member pages including my home page index.php.
however it creates a continuous redirect and does not load the page, it says the web
Probably because the header is included as well in the index, right? You can check for that on the condition before redirecting:
<?php
session_start();
include 'config.php';
if (empty($_SESSION['user']) && parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) != '/index.php') {
header('Location: index.php');
exit;
}
?>
You could set an array in your config.php with which pages need be validate and then compare with current page to define if will validate.
For example:
$member_pages = array('dashboard', 'member-page', 'etc');
$current = $_SERVER['REQUEST_URI'];
if (empty($_SESSION['user']) && array_search($current, $member_pages) !== FALSE) {
header('Location: index.php');
exit;
}
Hope it helps!
Within member pages do:
$memberOnly = true;
include 'header.php';
and in header.php:
if (isset($memberOnly)) {
if (empty($_SESSION['user'])) {
header('Location: index.php');
exit;
}
}
In public pages (non-member available) you simply:
include 'header.php'
without worrying about $memberOnly
If i understand your problem correctly, your header.php file is included in every page. Though this header.php file contains code which is executed:
header.php:
<?php
// This code is executed whenever you include this file
session_start();
include 'config.php';
if (empty($_SESSION['user'])) {
header('Location: index.php');
exit;
}
?>
You get a redirection loop, what means that this code is also executed in the index.php page. Maybe the header.php file is included in the index.php file as well.
If you would extract the code to a function and call it only in the pages which require a logged in user, you would avoid this loop.
header.php:
<?php
// The code in this function is not called automatically when the file is included
function redirectToLoginIfNecessary()
{
if (!isset($_SESSION['user'])) {
header('Location: index.php');
exit;
}
}
?>
index.php:
<?php
session_start();
include 'header.php';
// Public accessible pages do not call the function
...
?>
secret.php:
<?php
session_start();
include 'header.php';
// Protected pages do call the function
redirectToLoginIfNecessary();
...
?>
This works for me.
Using header is best, but has to be used before any other content is sent to the browser. Which, for me, developing in schmurdpress, makes it hard to implement.
if ( is_user_logged_in() ) {
echo 'Cool!';
} else {
$url = "https://yourdomain.com/log-in/";
echo '<META HTTP-EQUIV="refresh" content="0;URL=' . $url . '">';
}
You redirect index.php to index.php - if the access file is index.php your redirection shouldn't be fired.
<?php
session_start();
include 'config.php';
$basename = substr(strtolower(basename($_SERVER['PHP_SELF'])),0,strlen(basename($_SERVER['PHP_SELF']))-4);
if ((empty($_SESSION['user'])) && ($basename!="index")) {
header('Location: index.php');
exit;
}
?>
Add this check just before the redirect
if ($_SERVER["PHP_SELF" ] != "index.php")

Wordpress wp_redirect not redirecting

Hello guys badly need help here, I have created a custom template in wordpress. Now I also used a session variable to check status which I placed in the index.php, if session variable is 1 then redirect to a specific php file. But wp_direct() doesn't seem to work when I uploaded and installed the custom theme on my wordpress site. Check my codes:
<?php
session_start();
if ((isset($_SESSION['stat']) && $_SESSION['stat'] == '1')) {
wp_redirect('http://example.com/wp-content/themes/customtheme/newpage.php', 301);
exit;
?>
Code above only displays a blank page. Any help would be much appreciated.
UPDATE [SOLVED]: I managed to fix it, instead of using wp_redirect() I used a javascript method for redirection. Working code:
<?php
session_start();
if ((isset($_SESSION['stat']) && $_SESSION['stat'] == '1')) {
echo '<script type="text/javascript">window.location.href = "http://example.com
/wp-content/themes/euro/newpage.php";</script>';
?>
First you have assign newpage.php template in your page and then after you have to pass page id in url which you are assigned page newpage.php template. Here i passed "10".
<?php
session_start();
if ((isset($_SESSION['stat']) && $_SESSION['stat'] == '1')) {
wp_redirect('http://example.com/?page_id=10', 301);
exit;
?>
Try following code May be this will help,
session_start();
if ((isset($_SESSION['stat']) && $_SESSION['stat'] == '1')) {
ob_clean();
wp_redirect('http://example.com/wp-content/themes/customtheme/newpage.php', 301);
exit;
}
Make this file "newpage.php" as a template with name "newpage" and then create a page in backend then use this template for that page and then use the url of that page in wp_redirect() function.
Just use this functional as per below:
ob_clean();
$url = get_home_url() . '/login';
wp_redirect($url);
exit();

Session redirect loop on login page work-around advice

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

use php to display log in and log out link according to active session

This is the code i have at the moment but will not work, displays log out button when logged in only on one page then logs user out automatically ?
<?php
if(!session_is_registered(myusername))
{
echo '<b>Log In</b>';
}
else
{
echo '<b>Log Out</b>';
}
?>
You had forgotten to do session_start() out of many things, and please make sure to share that, on every one of your pages, where you want to enable session protection.
<?php
session_start();
if(!isset($_SESSION['username']) && empty($_SESSION['username']))
{
echo '<b>Log In</b>';
}
else
{
echo '<b>Log Out</b>';
}
?>
session_is_registered is deprecated. Try using $_SESSION instead
if ($_SESSION["isLoggedIn"]) {
// Log out HTML goes here
} else {
// Log in HTML goes here
}
You'll need to include session_start() at the top of all of your files and you can set $_SESSION["isLoggedIn"] just like any other variable: $_SESSION["isLoggedIn"] = TRUE

Categories