Page 1 of 1

controlling page access

Posted: Wed Nov 20, 2002 12:16 pm
by CrazyJimmy
Hi,

I have a script which validates users using a mysql database, when they are validated they are directed to control.php. this works fine, but how can I stop people just putting the url for control.php and accessing it directly?

Dave

Posted: Wed Nov 20, 2002 1:02 pm
by hedge
You need a 'gatekeeper' at the top of each script to verify (usually based on a session var) that they are authenticated.

The bigger problem is non-script content such as .xls files or such, you need to store them out of the htm root and then use a helper script that sends the headers and content to them after checking authentication.

Posted: Wed Nov 20, 2002 3:50 pm
by oldtimer
Once you have them login you can have something like this below.
So unless they have a session they will

if (session_is_registered("valid_user"))
{ // Start of main page.


} // end of main page
else
{
echo "Sorry, You are either not logged in or your session has expired.";
}

Posted: Thu Nov 21, 2002 2:32 am
by twigletmac
If you are using PHP 4.1 or above then you should use something like:

Code: Select all

if (!empty($_SESSIONї'valid_user'])) {
instead of

Code: Select all

if (session_is_registered("valid_user"))
Mac

Posted: Thu Nov 21, 2002 9:51 am
by oldtimer
So something like this then?


if (!empty($_SESSION['valid_user']))
{
echo "Sorry, but you are not signed in.";
} else {

Main body goes here

}

Posted: Thu Nov 21, 2002 10:00 am
by twigletmac
Not quite, empty() checks whether a variable is set and whether it is equal to an empty string or 0, if the variable is not set or is equal to an empty string or zero then the function returns true. So you'd need to adjust the code above to something like:

Code: Select all

if (empty($_SESSIONї'valid_user'])) { //note no ! before empty() call
    echo 'Sorry, but you are not signed in.'; 
} else { 
    //Main body goes here 
}
Mac

Posted: Thu Nov 21, 2002 10:27 am
by oldtimer
Okay I understand that. But the ! came from your post. I just pasted it.

Posted: Thu Nov 21, 2002 1:26 pm
by CrazyJimmy
Got it working now thanks. Sessions are great, I never realised how easy they were to use :)

Posted: Thu Nov 21, 2002 1:34 pm
by oldtimer
I can do normal session not to bad. My next thing is learning to use the cookies and maybe storing the sessions inside a DB and authenticate it via that way too.

Posted: Fri Nov 22, 2002 1:58 am
by twigletmac
oldtimer wrote:Okay I understand that. But the ! came from your post. I just pasted it.
That's because I adjusted the example that you had posted in which to replace session_is_registered() you need to check that the variable is not empty().

Mac

Posted: Fri Nov 22, 2002 10:04 am
by oldtimer
Very strange as I just pasted from your post.