Storing Passwords There are many better places to store usernames and passwords than inside the script.. Using a database to store usernames and passwords would not make the script much
Trang 1<?php } else if($name=='user'&&$password=='pass') {
// visitor's name and password combination are correct echo '<h1>Here it is!</h1>';
echo 'I bet you are glad you can see this secret page.';
} else { // visitor's name and password combination are not correct echo '<h1>Go Away!</h1>';
echo 'You are not authorized to view this resource.';
}
?>
The code from Listing 14.1 will give you a simple authentication mechanism to allow authorized users to see a page, but it has some significant problems
This script
n Has one username and password hard-coded into the script
n Stores the password as plain text
n Only protects one page
n Transmits the password as plain text These issues can all be addressed with varying degrees of effort and success
Storing Passwords
There are many better places to store usernames and passwords than inside the script
Inside the script, it is difficult to modify the data It is possible, but a bad idea to write a script to modify itself It would mean having a script on your server, which gets
execut-ed on your server, but is writable or modifiable by others Storing the data in another file on the server will let you more easily write a program to add and remove users and
to alter passwords
Inside a script or another data file, there is a limit to the number of users you can have without seriously affecting the speed of the script If you are considering storing and searching through a large number of items in a file, you should consider using a database instead, as previously discussed As a rule of thumb, if you want to store and search through a list of more than 100 items, they should be in a database rather than a flat file
Using a database to store usernames and passwords would not make the script much more complex, but would allow you to authenticate many different users quickly It Listing 14.1 Continued
Trang 2would also allow you to easily write a script to add new users, delete users, and allow users to change their passwords
A script to authenticate visitors to a page against a database is given in Listing 14.2
Listing 14.2 secretdb.php—We Have Used MySQL to Improve Our Simple
Authentication Mechanism
<?php if(!isset($HTTP_POST_VARS['name'])&&!isset($HTTP_POST_VARS['password'])) {
//Visitor needs to enter a name and password
?>
<h1>Please Log In</h1>
This page is secret.
<form method="post" action="secretdb.php">
<table border="1">
<tr>
<th> Username </th>
<td> <input type="text" name="name"> </td>
</tr>
<tr>
<th> Password </th>
<td> <input type="password" name="password"> </td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Log In">
</td>
</tr>
</table>
</form>
<?php } else { // connect to mysql
$mysql = mysql_connect( 'localhost', 'webauth', 'webauth' );
if(!$mysql) {
echo 'Cannot connect to database.';
exit;
} // select the appropriate database
$mysql = mysql_select_db( 'auth' );
if(!$mysql) {
Trang 3} // query the database to see if there is a record which matches
$query = "select count(*) from auth where
name = '$name' and pass = '$password'";
$result = mysql_query( $query );
if(!$result) {
echo 'Cannot run query.';
exit;
}
$count = mysql_result( $result, 0, 0 );
if ( $count > 0 ) {
// visitor's name and password combination are correct echo '<h1>Here it is!</h1>';
echo 'I bet you are glad you can see this secret page.';
} else { // visitor's name and password combination are not correct echo '<h1>Go Away!</h1>';
echo 'You are not authorized to view this resource.';
} }
?>
The database we are using can be created by connecting to MySQL as the MySQL root user and running the contents of Listing 14.3
Listing 14.3 createauthdb.sql—These MySQL Queries Create the auth Database, the
auth Table, and Two Sample Users
create database auth;
use auth;
create table auth (
name varchar(10) not null, pass varchar(30) not null, Listing 14.2 Continued
Trang 4insert into auth values ('user', 'pass');
insert into auth values ( 'testuser', password('test123') );
grant select, insert, update, delete
on auth.*
to webauth@localhost
identified by 'webauth';
Encrypting Passwords
Regardless of whether we store our data in a database or a file, it is an unnecessary risk
to store the passwords as plain text A one-way hashing algorithm can provide a little more security with very little extra effort
The PHP function crypt()provides a one-way cryptographic hash function.The prototype for this function is
string crypt (string str [, string salt])
Given the string str, the function will return a pseudo-random string For example, given the string "pass"and the salt "xx",crypt()returns "xxkT1mYjlikoII".This string cannot be decrypted and turned back into "pass"even by its creator, so it might not seem very useful at first glance.The property that makes crypt()useful is that the output is deterministic Given the same string and salt,crypt()will return the same result every time it is run
Rather than having PHP code like if( $username == 'user' && $password == 'pass' ) {
//OK passwords match }
we can have code like if( $username == 'user' && crypt($password,'xx') == 'xxkT1mYjlikoII' ) {
//OK passwords match }
We do not need to know what 'xxkT1mYjlikoII'looked like before we used crypt()
on it.We only need to know if the password typed in is the same as the one that was originally run through crypt()
Listing 14.3 Continued
Trang 5As already mentioned, hard-coding our acceptable usernames and passwords into a script is a bad idea.We should use a separate file or a database to store them
If we are using a MySQL database to store our authentication data, we could either use the PHP function crypt()or the MySQL function PASSWORD().These functions do not produce the same output, but are intended to serve the same purpose Both crypt()
and PASSWORD()take a string and apply a non-reversible hashing algorithm
To use PASSWORD(), we could rewrite the SQL query in Listing 14.2 as
select count(*) from auth where name = '$name' and pass = password('$password')
This query will count the number of rows in the table auththat have a name value equal to the contents of $nameand a pass value equal to the output given by
PASSWORD()applied to the contents of $password Assuming that we force people to have unique usernames, the result of this query will be either 0or 1
If you look back at Listing 14.3 you will see that we have created one user (‘user’) with an unencrypted password and another user with an encrypted one (‘testuser’) to illustrate the two possible approaches
Protecting Multiple Pages
Making a script like this protect more than one page is a little harder Because HTTP is stateless, there is no automatic link or association between subsequent requests from the same person.This makes it harder to have data, such as authentication information that a user has entered, carry across from page to page
The easiest way to protect multiple pages is to use the access control mechanisms provided by your Web server.We will look at these shortly
To create this functionality ourselves, we could include parts of the script shown in Listing 14.1 in every page that we want to protect Using auto_prepend_fileand
auto_append_file, we can automatically prepend and append the code required to every file in particular directories.The use of these directives was discussed in Chapter 5,
“Reusing Code and Writing Functions.”
If we use this approach, what happens when our visitors go to multiple pages within our site? It would not be acceptable to require them to re-enter their names and pass-words for every page they want to view
We could append the details they entered to every hyperlink on the page As user-names might have spaces, or other characters that are not allowed in URLs, we should use the function urlencode()to safely encode these characters
There would still be a few problems with this approach though Because the data would be included in Web pages sent to the user and the URLs they visit, the protected pages they visit will be visible to anybody who uses the same computer and steps back through cached pages or looks at the browser’s history list Because we are sending the