Link to home
Start Free TrialLog in
Avatar of deeayrian
deeayrianFlag for United States of America

asked on

Allow access to page based on PHP Session variable

I have a pretty easy task to accomplish but for some reason it doesn't seem to want to work for me.  I am creating a website that allows access to certain pages, based on an end user's role.  So, if a person has the sales role (stored in the database), then they are allowed access to the sales page.  However, if they do not have the sales role, then they are directed to the salesUnauthorized.php page.  

Please see my code below.  It checks to see if the session is set to sales.  The session is created in the previous page and the role is pulled from the database for that user.  For some reason, when I use the code below, it directs me to the unauthorized page, even when my session variable is sales.  If I change it to == instead of !=  it then allows me to see the sales page, when it should direct me to the unauthorized page.  

Can someone please tell me what I am missing?  
Thank you.
<?php 		if ($_SESSION["access"] != "sales"){
			header("Location: salesUnauthorized.php");
			exit;} ?>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I'm not convinced that $_SESSION["access"] actually contains "sales"

Try
var_dump ( $_SESSION );

Open in new window

to see how the variable is really set.

Also look at the end of your error_log file for error messages.



Yes, what Ray said too.  Make sure you have session_start() on that page.  Either way, var_dump is your friend.
Avatar of deeayrian

ASKER

I am so embarrassed that I overlooked the session start command.  I just started working with sessions and my instructor warned us about ensuring we start them on every page.

Thank you for your quick response!  Much appreciated.
Ha, ha, ha!  You're just like the rest of us.  To get around this I have a file that I include() at the top of every script, and it has session_start() along with all of my classes and functions and define() statements.

The next thing you will forget, if you are like me, is the use of $this-> inside your class definitions.

Don't worry -- it becomes habit in time and you will be off to the races!

Thanks for the points, ~Ray

I was echo-ing out the Session variable so I knew it was containing sales like it should.  I am using includes in my project actually, but since I forgot about the session start command, I didn't even think to put it in my header include.  I will go ahead and do that!  Thank you for the great tip.
Yeah, PHP should make the $_SESSION variable immutable and undefined if you have not issued session_start(), but alas...

All the best, ~Ray