Hi I have following files:
login.php, index.php, header.php, footer.php, restrictaccess.php
restrictaccess.php has following code:
<?php
session_start();
if (!(isset($_SESSION['user']) && $_SESSION['user'] != ''))
if (!(isset($_SESSION['access']) && $_SESSION['access'] != ''))
{
header ("Location: login.php");
exit();
}
if($_SESSION['access']=="2" ) {
echo 'You are logged on as Manager';
}
if($_SESSION['access']=="1" ) {
echo 'You are logged on as Restricted user';
}
?>
restrictaccess.php, header.php and footer.php is included on every page accept login.php.
Both header and footer also includes restrictaccess.php; will this cause any problem ? Is there anyway so that such includes will only be loaded once ?
Currently when someone logon the message "You are loged on as Manager/Restricted user" is displayed thrice.
Your help will be much appreciated, thank you.
Try using require_once() to include your file. This method checks wether the file was already included.
PHP manual
UGLY method
Use require_once or include_once for restrictaccess.php
Better method
Change restrictaccess.php to only:
<?php
if (!(isset($_SESSION['user']) && $_SESSION['user'] != ''))
if (!(isset($_SESSION['access']) && $_SESSION['access'] != ''))
{
header ("Location: login.php");
exit();
}
?>
Then use session_start() at the top of every client page (the pages that user can browse to like index.php).
Use the code about "You are logged-in as ..." only in the header.php (or wherever it make sense to display.
UPDATE
You can include the above restrictaccess.php anywhere in you files BUT you have to make sure that there is no data sent to the client prior to the header ("Location: login.php"); bit (i.e. if you have any echo, print_r or var_dump... before the header ("Location: login.php"); then PHP will generate an error)
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 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")
<?php
1.
if (isset($_SESSION['username'])) {
header('Location: log.php');
}
2.
if (session_id() != '') {
header('Location: log.php');
}
3.
if(isset($_SESSION['username']))
{
header("Location: log.php");
exit;
}
4.
if (session_status() != PHP_SESSION_NONE) {
header("Location: log.php");
}
?>
I want my php to redirect to from main.php to log.php if the session is live. I want to achieve an effect where logged on users cannot access a page and once they try to do it via a url they get automatically redirected to a different page.
Above are the attempts I did and did not work for me.
You need session_start.
session_start();
if(!isset($_SESSION['username'])) {
header("Location: log.php");
exit;
}
I think that you miss the call to php session_start().
Try this:
<?php
session_start();
if (isset($_SESSION['username'])) { header('Location: log.php'); }
?>
And be sure that your use logged account.
although it's 4 years later,I solve this problem just now.
Please make sure all these matter:
1. All the pages have to set the below parameter in the beginning
if (session_status() == PHP_SESSION_NONE) {session_start();}
Adding the session variable must use $_SESSION in order to set the session as globally
exit(); must be added after header("location: $URL ");
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
What i am trying to do is redirect the logged in member to index2.php if he try to move back to index.php
I put this piece of code on the very top of index.php :
<?php
session_start();
if (isset($_SESSION['uid'])) {
header ("Location :index2.php");
} else {
session_unset();
session_destroy();
}
the expected behavior for this code is to redirect the member back to index2.php but it does not and index.php is running , how can i fix that ?
Perhaps this is because of your space within the code? Try this...
<?php
session_start();
if (isset($_SESSION['uid'])) {
header ("Location: index2.php");
} else {
session_unset();
session_destroy();
}
Notice the change to location: