php - session, check for admin - php

I have everything working on my login except for the admin user.
When I try to navigate to my admin.php I get "Must be logged in" even if I am already logged in as an admin.
When I click the admin link, I first go to checkAdmin.php which is the code below.
<?php
if($_SESSION['userEmail'] != 'admin#hotmail.com') {
echo "<center><font face='Verdana' size='2' color=red>Must be logged in</font> <br><a href=index.php>Login Here</a></center>";
exit;
}
?>
Am I doing something wrong on this?
Thanks.
I have session_start(); at the top of my admin.php page.
I used print_r($_SESSION); and got this line, so it has the right value.
Array ( [userEmail] => admin#hotmail.com )
Also, if I add session_start(); to the checkAdmin.php then the screen just sits at checkAdmin, when I click to go to the admin page.
The admin.php has this at the top
session_start();
require "checkAdmin.php";
include("db_info.php");

Make sure you have called session_start() before checking session variables.

you probably did not set $_SESSION['userEmail'] while the login-process
also session_start() has to be called.
I'd check what really is in your session with print_r($_SESSION);

Did you try to add session_start() ? You have to do it before looking for session variables.
Try with it :
<?php
session_start();
if($_SESSION['userEmail'] != 'admin#hotmail.com') {
echo "<center><font face='Verdana' size='2' color=red>Must be logged in</font> <br><a href=index.php>Login Here</a></center>";
exit;
}
?>

use var_dump() instead of print_r. pay carefull attention to the reported string length, because some characters arent visible, but will obviously cause a string comparison to fail.
you likely have a stray whitespace character

Related

Trying to redirect based on session variable existence but it's not working

I want to ensure that an HTML page only appears if the user has logged in. I'm trying to do it by setting a session variable from the login page then checking if that variable exists when the HTML page is loaded.
This is my code at the very top of the HTML page:-
<?php
session_start();
if (!isset($_SESSION['checks'])) {
header("location: http://localhost/project/fail.php");
}
?>
It doesn't redirect! Nothing happens at all except that the HTML page gets loaded.
Can anyone help please?
Thank you all for your helpful suggestions. The snippet I posted shows the very first lines: i.e. session_start(); is the very first line.
By moving the var check snippet from the session_start() segment and making a separate php check snippet immediately after the body tag, everything works as expected.
You can use header function : https://www.php.net/manual/en/function.header.php
Referring to it :
<?php
session_start();
if (!isset($_SESSION['checks'])) {
header("Location: http://localhost/project/fail.php");
}
?>
make sure that session_start() always come at the first line
if(!isset($_SESSION['checks'])){
header('location: fail.php');
}
I believe your problem is on the login page... Although, if I were to talk about this page, consider trying the following code instead of your snippet first. If it gives the desired outcome then you will know that the problem is with your header and not the session:
<?php
session_start();
if (!isset($_SESSION['checks'])) {
echo "not logged in";
}
?>
Do make sure you're referring to the correct session variable if this code doesn't work and feel free to share how you are starting this session on your login page.

Php login script won't wrap around php

I am trying to verify that a user has logged in before showing them the page, using the method below, while the if/else method works when wrapped around plain html, it is failing when there is php involved. I am a novice by the way. What happens is the page simply loads as if the two tags below weren't there...which would be fine had I previously logged in, but I hadn't.
<?php
session_start();
if(isset($_SESSION['user'])) {
?>
HTML/PHP Page goes here.
<?php
} else {
header("Location: cms/admin/loginreadmode.php");
}
?>
Thanks in advance,
You can debug just below your session_start(); by printing your session:
echo '<pre>';
print_r($_SESSION);
die();
If $_SESSION['user'] isn't showing up in your array it isn't be set.
You can do this like this:
session_start();
$_SESSION['user'] = true;
Are you sure that you have add session support in every page?
if (!isset($_SESSION)) {
session_start();
}
This code should be working, so mistake is probably somwhere else I suggest checking if you set $_session["user] after login.
You should also replace your not-working code part with simple
echo "hello";
to chek it.
1) That is not a great method of checking whether a user is logged in, purely checking whether a user sessions exists can end up causing a lot of problems. Storing the ID in the sessions and then checking whether the ID is valid may be a better way,
2) When I copy the code above into a test document it goes straight to the redirect page in the else statement. This is down to the user session not being set, as soon as I set the user session before the code is executed it works fine. I see 'HTML/PHP Page goes here.'.
Setting the user session:
$_SESSION['user'] = 'TestUser';
You can change the code at the top of the page to be
<?php
session_start();
if(!isset($_SESSION['user'])) {
header("Location: cms/admin/loginreadmode.php");
die();
}
?>

Session not set till page reload?

So after a LOT of trial and error, I set up something to test whether my session is set or not, which looks like this :
<?php
session_start();
if (isset($_SESSION['email'])) {
echo "Logged In!";
}
else {
echo "NOT LOGGED IN!";
}
?>
And what I realize is that after Login ( which redirects to the site's homepage) The session is not set until I reload the entire homepagepage.
Has anyone experienced anything like this and/or knows how to get around such a problem?
Thanks in advance!
This snippet of code works for me as a test. Make sure your order of operations matches this. If that does not work, make sure you are allowing cookies in your browser. Failing that, there could be something screwy about your PHP/Apache configuration.
<?php
session_start();
if (!isset($_GET['test']))
{
$_SESSION['email'] = "something ".time();
header('location:?test');
die;
}else{
echo 'Value: "' .$_SESSION['email']. '"';
echo '<br /><br />< Do again';
die;
}
?>
Your pages need to be set up like so in this order (particularly the session_start()):
login.php
<?php
session_start();
// 1) Some code here to check database if username and password check out
// 2) If username and password check out and validation is good
// 3) Redirect to your next page (index.php in this case)
?>
index.php (home page)
<?php
session_start();
?><!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1><?php
if(isset($_SESSION['email'])) { ?>
EMAIL IS SET!! Great job!
<?php } else { ?>
UM...No..<?php } ?></h1>
</body>
</html>
I was having a horrible time with this. I have an index page that loads every time and inside a content div loads specific php scripts via include. I control the navigation of the website in this way by passing GET variables to the index.html, so my index page loads every single time no matter what content you're viewing. The very first line of index.html was:
<?php
session_start();
Some of my php scripts running as includes on the index page would set session variables then redirect to the index page and the session variable would not be there,, or they would not be set to what they should be. It was driving me mad, I could ctrl-F5 and sometimes they would show up and sometimes not. The only thing I can figure was that it was somehow opening different sessions for different urls that were in the address bar (by different urls I mean ones with different GET parameters. Simply putting this at the beginning of my index.html solved all my problems. I assume this causes the same session to open each time:
<?php
session_name('SessName');
session_start();
Thanks for all the help guys, but I found the problem.
Apparently I have to be extremely specific with my url in the redirect file.
I had header('location: http://domain.com');
instead of
header('location: http://www.domain.com');
...facepalm

How can i get the session start username to echo out

Iam having issues echoing the session username and have no idea were to start any more cause every thing i have tried keeps saying string to array conversion but idk how to get this to correctly work. here is the code that would check for the loged in saying you logged in would you like to log out.
if(isset($_SESSION['username'])&& !empty($_SESSION['username'])){
echo "<P id='loged'>your loged in would you like to log out</p>";
echo'log out';
}else{
include 'logform.php';
}
You probably want to call session_start() before the $_SESSION variable will be available.
You just want to echo the username?
echo "Hello " . $_SESSION['username];
I suppose the following answers your question...
echo $_SESSION['username'];
...but you will also want to use session_start() first.
Also, no need to use isset() and !empty(), as empty() checks if it is set first. All you really need is:
if(!empty($_SESSION['username']))
You forgot to mention session_start() in the begining.
session_start(); //add this in the begining of the file.
echo $_SESSION['username']; //this will display username
Try this:
call the function session_start() at beginning of the page and then check the $_SESSION array using
echo '<pre>';
print_r($_SESSION);
after that you see all the indexes set in session variable.
Thanks

php sessions not working correctly

Hello i am having problems holding sessions from page to page, code worked on my previous servers running php5 but not on my recent server, i am wondering whether its a bug?
<?php
session_start();
$_SESSION['session'] = $_POST['session'];
header("location: www.mysite.com/page1.php");
?>
<?php
session_start();
echo "Good morning" . $_SESSION['session']; //returns empty session always.
?>
ANy ideas? session is held on first page but not on the second.
In case you missed it, make sure you do a session_start() at every page you're using the $_SESSION variable.
You should check your php.ini file and see what's going on.
Make sure session.use_cookies = 1 and session.save_handler = files.
Use this test page to see whether it's a general PHP problem or just your code.
<?php
session_start();
if(isset($_SESSION)){
echo "Session variable exists<br/>";
if(!isset($_SESSION['test'])){
$_SESSION['test'] = "Success!";
echo "Variable has been set, refresh the page and see if stored it properly.";
}else{
echo $_SESSION['test'];
}
}else{
echo "No session variable has been created.";
}
?>
If that worked, then it's got to do with your code.
If you're setting your session variable to $_POST['session'] am I to assume you submitted a form with an input with the name session?
This setup should work.
index.php
<form action='page0.php' method='POST'>
<input type='hidden' name='session' value='SPAAAAACE' />
<input type='submit' />
</form>
Page0.php
<?php
session_start();
$_SESSION['session'] = $_POST['session'];
header("location: www.mysite.com/page1.php");
?>
Page1.php
<?php
session_start();
echo "Good morning" . $_SESSION['session'];
?>
For completeness and debugging purposes
In case you are using cookie-less sessions, you have to manually add the SID (session id) to the header redirect like this
header("location: www.mysite.com/page.php?".htmlspecialchars(SID));
If the problem still persists, it could be a permission issue.
Maybe you're not allowed to read the session file stored on the server?
Update: OP commented that it was a permission issue and the problem is now resolved
Turn on error reporting temperately with:
error_reporting(E_ALL) This may spit out an error related to your problem. Most likely an undefined index session notice.
You should always have a check in place on Super Globals.
<?php
session_start();
$_SESSION['session'] = (isset($_POST['session']))?$_POST['session']:null;
header("Location: www.mysite.com/page1.php");
die;
?>
Your code seems correct though I'm pretty sure $_POST['session'] is empty.
You should try this :
<?php
session_start();
$_SESSION['session'] = 'John Doe';
header("location: www.mysite.com/page1.php");
?>
<?php
session_start();
echo "Good morning" . $_SESSION['session']; //returns empty session always.
?>
To see if this works or not. I guess it will.
IF not, take a look at your cookies, maybe they are disabled.
Then, if it works, I probably because $_POST['session'] is null or empty, are you sure you posted something like <input type="text" name="session" /> ?
You need to pass the session id with the redirect.
Also make sure you use session_start() at the top of EVERY page that needs a session
First try using
<?php session_start();
instead of
<?php
session_start();
If the problem still exists, then open your script in Netbeans editor and see whether any unexpected characters found at very beginning of the the script.
In addition, please make sure that $_POST['session'] has a value to assign in $_SESSION['session'].
You will have to call
session_start();
on the first line of every page you want to retain the session in

Categories