PHP Basics: HTTP Authentication – Security

Well we’re back here again, doing some ‘PHP Jazz’ as my mrs would say, then again she’d use the word ‘Jazz’ in any context…Crazy fool.

Note: If you copy and paste any code here, you will need to make sure you replace the quotation markse (“) with standard ones, as when you copy it from here it will bugger up.

Lets do this!

What is PHP HTTP Authentication?

Well lets warn you, that its only going to work if you have it intalled as an Apache module on your server. Its not tricky stuff but go and do that first, or check it out. PHP info I’m sure will tell you. It won’t work if you just got CGI version running.

You can use the header() function in php to send the Autentication request. Ie, this will prompt you before the rest of the page loads, and the whole point of the security. It’ll basically just pop up in a window, asking for username and password, just like it does when you have been on other websites using htaccess (it looks like the username / password prompt when you try and and access a network share without credentials in windows.

Once the user has popped in their username and password. The PHP script will then be called again using predefined variables PHP_AUTH_USER, PHP_AUTH_PW and AUTH_TYPE set the user name, password and authentication type. These variables are found when you use $_SERVER (it’ll show you them in programes like PHP designer and Dreamweaver), or $HTTP_SERVER_VARS arrays. These 2  badboys are super globals. To be honest I’d be more inclined to use $_SERVER…

We’re going to take a look at just Basic HTTP Auth, if you wanna take it further, go research it.

<?php
if (!isset($_SERVER['PHP_AUTH_USER'
])) {
header(‘WWW-Authenticate: Basic realm=”Wuup Security Guard”‘
);
header(‘HTTP/1.0 401 Unauthorized’
);
echo
‘Oh come on dude, you’re not even trying, that was the cancel button!’
;
exit;
} else {
echo
“<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>”
;
echo
“<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>”
;
}
?>

Now that aint stopping anyone getting in, but with a bit of MD5 encryption, matching up usernames and passwords in a mysql database, and you’re well onto a good thing. It gets you started.

Hope this was useful to you.

Cheers!

Wuup Team

Tags: , , , , , , , , , ,

Author:Alan Hamlyn

-- Alan Hamlyn Founder of Wuup