PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
I am trying to create a secure area of my site where only 2 people are allowed. For now its a basic protection but i can't get it to work. What I am trying to do is make the script check the users session to see if it matches 1 of 2 names. If so it proceeds, else an error message is displayed. All worked great but when i tried the script out with different usernames it still let me in. What am I doing wrong here. Script below:
<?php
$name = $_SESSION['username'];
if (isset($_SESSION['username']) != 'Joe' || isset($_SESSION['username']) != 'Paul')
{
echo "<b>Sorry, You are not authorized to access this area of the site.<p></b>";
echo "Click <A href='???'>here</A> to go to the index page!";
exit;
}
else
{
echo "great!";
exit;
}
<?php
$name = $_SESSION['username'];
if (isset($_SESSION['username'] = false || ($_SESSION['username'] != 'Joe' && $_SESSION['username'] != 'Paul'))
{
echo "<b>Sorry, You are not authorized to access this area of the site.<p></b>";
echo "Click <A href='???'>here</A> to go to the index page!";
exit;
}
else
{
echo "great!";
exit;
}
<?php
$allowed = array('Joe', 'Paul');
if (empty($_SESSION['username']) || !in_array($_SESSION['username'], $allowed))
{
echo '<b>Sorry, You are not authorized to access this area of the site.<p></b>';
echo 'Click <A href="???">here</A> to go to the index page!';
exit;
} else {
echo 'great!';
exit;
}
?>
Just for future record;
A) if the session 'username' is set with FOO, it will pass. As the next post shows, a variant of empty() usage is preferred.
B) we are setting the session to 'false' (likely just spelling error).
This outputs "0", but it looks like it ought to output "5". The reason is that even though I'm doing it in an "if" statement, the phrase "$testMe = 0" sets the value to 0. What I should say is:
if ($testMe == 0) echo "It's zero!";
And there's even a === which means "is it equal, and is it of the same datatype", I think.
I tried to edit your post to change that and leave a smaller note of why, but apparently, or so I think, mark made his post at the same time giving me a wierd update post error...
You are by all means not alone. I can't remember all the times I've done this myself either...