Create a new PHP script with the following code: < ?phprequire ‘db.inc.php’; $query = ‘CREATE TABLE IF NOT EXISTS site_user user_id INTEGER NOT NULL AUTO_INCREMENT, username VARCHAR20 N
Trang 1$_SESSION[‘username’] = $username;
$_SESSION[‘logged’] = 1;
header (‘Refresh: 5; URL=’ $redirect);
echo ‘ < > You will be redirected to your original page request < /p >
echo ‘ < > If your browser doesn\’t redirect you properly ‘ ‘automatically, < a href=”’ $redirect ‘” >
click here < /a > < /p >
die();
} else { // set these explicitly just to make sure $_SESSION[‘username’] = ‘’;
$_SESSION[‘logged’] = 0;
$error = ‘ < > < strong > You have supplied an invalid username and/or ‘
‘password! < /strong > Please < a href=”register.php” > click here ‘ ‘to register < /a > if you have not done so already < /p >
} }}
}
? < form action=”login.php” method=”post” >
< table >
< tr >
< td > Username: < /td >
< td > < input type=”text” name=”username” maxlength=”20” size=”20”
value=” < ?php echo $username; ? > ”/ > < /td >
< /tr > < tr >
< td > Password: < /td >
< td > < input type=”password” name=”password” maxlength=”20” size=”20”
value=” < ?php echo $password; ? > ”/ > < /td >
Trang 24 Save the file as login.php
5 Navigate to the secret.php page you created Because you haven ’ t logged in yet, the
auth.inc.php file you included redirects you to the login.php page, as shown in
Figure 12 - 3
Figure 12-3
6 Try using incorrect login information so you can see how the page works You will see a
screen similar to the one shown in Figure 12 - 4
Trang 37 Now, input the correct information: wroxbooks for the username and aregreat for the password You are redirected to the page you originally requested, because you supplied the correct information You will see a screen similar to Figure 12 - 5
Figure 12-4
Trang 4How It Works
The PHP pages you just created are used to authorize a user to view a certain page of your site When
you navigate to secret.php , the included auth.inc.php file checks to see if you have successfully
started a session by logging in If not, you are redirected to the login page This is the magic line of
code that does the checking:
if (!isset($_SESSION[‘logged’]) || $_SESSION[‘logged’] != 1) {
The $ _SESSION[ ‘ logged ’ ] is the variable you are checking for, and the value 1 is another way of
checking for true
Right now, you have a username and password hard - coded into your page If you want numerous
users, you would have to edit your page accordingly and add those values for those users
if (!empty($_POST[‘username’]) & & $_POST[‘username’] == ‘wroxbooks’ & &
!empty($_POST[‘password’]) & & $_POST[‘password’] == ‘aregreat’) {
This is a very useful way to protect your PHP files to limit use to logged - in users and administrators
However, there is one major drawback that you will resolve later when you integrate the database
driven system: Hard - coded usernames and passwords are only manageable when the number of users
Figure 12-5
Trang 5with login information is small As the number of users grows, the credentials will become more cumbersome and unwieldy to manage
In the next sections, you learn how you can use PHP in conjunction with MySQL to create user - driven login systems You also learn how to allow for multiple administrators, multiple usernames and passwords, and privilege levels that can be managed with the MySQL database
Using Database - Driven Information
Before you can use database - driven logins, you obviously need to have the appropriate tables set up So first you will create the tables in your MySQL database You will also add a few sample user accounts for testing purposes
Try It Out Creating the Database Tables
1 Create a new PHP script with the following code:
< ?phprequire ‘db.inc.php’;
$query = ‘CREATE TABLE IF NOT EXISTS site_user ( user_id INTEGER NOT NULL AUTO_INCREMENT, username VARCHAR(20) NOT NULL,
password CHAR(41) NOT NULL,
PRIMARY KEY (user_id) )
ENGINE=MyISAM’;
mysql_query($query, $db) or die (mysql_error($db));
// create the user information table
$query = ‘CREATE TABLE IF NOT EXISTS site_user_info ( user_id INTEGER NOT NULL,
first_name VARCHAR(20) NOT NULL, last_name VARCHAR(20) NOT NULL, email VARCHAR(50) NOT NULL, city VARCHAR(20),
state CHAR(2), hobbies VARCHAR(255),
FOREIGN KEY (user_id) REFERENCES site_user(user_id)
Trang 6)
ENGINE=MyISAM’;
mysql_query($query, $db) or die (mysql_error($db));
// populate the user table
$query = ‘INSERT IGNORE INTO site_user
(user_id, username, password)
// populate the user information table
$query = ‘INSERT IGNORE INTO site_user_info
(user_id, first_name, last_name, email, city, state, hobbies)
VALUES
(1, “John”, “Doe”, “jdoe@example.com”, NULL, NULL, NULL),
(2, “Sally”, “Smith”, “ssmith@example.com”, NULL, NULL, NULL)’;
mysql_query($query, $db) or die (mysql_error($db));
echo ‘Success!’;
?
2 Save the file as db_ch12 - 1.php
3 Open db_ch12 - 1.php in your web browser PHP will execute the code to create the tables in
your database and then show you the success message if everything goes correctly
How It Works
First, you created an administration table named site user This is where you can keep track of the
administrators managing your system
$query = ‘CREATE TABLE IF NOT EXISTS site_user (
user_id INTEGER NOT NULL AUTO_INCREMENT,
username VARCHAR(20) NOT NULL,
password CHAR(41) NOT NULL,
PRIMARY KEY (user_id)
)
ENGINE=MyISAM’;
mysql_query($query, $db) or die (mysql_error($db));
Then, you created a second table named site_user_info to store additional information about your
administrators, such as their names, where they are from, and their hobbies:
$query = ‘CREATE TABLE IF NOT EXISTS site_user_info (
user_id INTEGER NOT NULL,
first_name VARCHAR(20) NOT NULL,
last_name VARCHAR(20) NOT NULL,
email VARCHAR(50) NOT NULL,
city VARCHAR(20),
Trang 7state CHAR(2), hobbies VARCHAR(255),
FOREIGN KEY (user_id) REFERENCES site_user(user_id) )
ENGINE=MyISAM’;
mysql_query($query, $db) or die (mysql_error($db));
You then added a couple of administrators in your tables, so you can begin to create the registration portion of your PHP code to allow users to register and log in, and update their information or delete their accounts if needed
$query = ‘INSERT IGNORE INTO site_user (user_id, username, password) VALUES
(1, “john”, PASSWORD(“secret”)), (2, “sally”, PASSWORD(“password”))’;
mysql_query($query, $db) or die (mysql_error($db));
$query = ‘INSERT IGNORE INTO site_user_info (user_id, first_name, last_name, email, city, state, hobbies) VALUES
(1, “John”, “Doe”, “jdoe@example.com”, NULL, NULL, NULL), (2, “Sally”, “Smith”, “ssmith@example.com”, NULL, NULL, NULL)’;
mysql_query($query, $db) or die (mysql_error($db));
If you looked at the records stored in site_user after running db_ch12 - 1.php , you will have noticed what looks like gibberish stored in the password column You aren ’ t storing the user ’ s actual password Rather, you are storing a hash representation of it, by using MySQL ’ s PASSWORD() function
You can think of hashing as a form of one - way encryption The algorithms that perform the hashing for you are quite complex, and guarantee that every time you hash the same value you will get the same gibberish - looking string as a result If the input values are off, even ever so slightly, then the result will be wildly different For example, when you hash the word “ secret ” with the PASSWORD() function, you get * 14E65567ABDB5135D0CFD9A70B3032C179A49EE7 But if you hash “ Secret ” you get * 0CD5E5F2DE02BE98C175EB67EB906B926F001B9B instead!
So how will you verify the user when he or she logs in to your web site and provides a username and password? Simple Remember, the hash will always be the same for the same value So all you need to
do is take a provided password and hash it with PASSWORD() Then, if that value matches the value stored in the database, you know the user entered the correct password You will see this in action shortly
It is a good idea to avoid storing the user ’ s actual password, if you can This way, if your database were to be compromised, the attacker would be faced with quite a task trying to figure out the users ’ passwords from the hash values Unlike encryption, hashing is a one - direction - only process That is, you cannot take a hash value and convert it back to the original value
Once the user has been authenticated, you can again use sessions to track the user and provide access to sensitive sections of your web site Let ’ s continue forward in building the user login system
Trang 8Try It Out Session Tracking with PHP and My SQL
In this exercise, you create a user login system that uses the database tables you created earlier You
will program it so that the user is required to input a username, password, first name, last name, and
e - mail address The other fields that will be stored in the site_user_info table will be optional
1 First, create an index page that looks for login information, similar to the one in the previous
example, but don ’ t include an authorization page, so that you can show different content
based on whether or not the user is logged in This allows the user the chance to log in, if he
or she wishes to Call this page main.php , and use the following code to create it:
2 Now, modify the main.php file as shown, so you can have different content show up,
depending on whether or not a user is logged in This first branch will be available when the
user is logged in, and will contain links to the users ’ own personal area (which you create
later), to allow them to update personal information or delete their account entirely The
second branch will simply contain some information about the benefits that registering
provides and explain how to go about registering:
Trang 9? < > Thank you for logging into our system, < > < ?php echo $_SESSION[‘username’];? > < /b > < /p >
< > You may now < a href=”user_personal.php” > click here < /a > to go to yourown personal information area and update or remove your information shouldyou wish to do so < /p >
< ?php} else { // user is not logged in
? < > You are currently not logged in to our system Once you log in,you will have access to your personal area along with other userinformation < /p >
< > If you have already registered, < a href=”login.php” > clickhere < /a > to log in Or if you would like to create an account,
< a href=”register.php” > click here < /a > to register < /p >
< ?php}
? /body >
< ?phpsession_start();
include ‘db.inc.php’;
$username = (isset($_POST[‘username’])) ? trim($_POST[‘username’]) : ‘’;
$password = (isset($_POST[‘password’])) ? $_POST[‘password’] : ‘’;
$first_name = (isset($_POST[‘first_name’])) ? trim($_POST[‘first_name’]) : ‘’;
$last_name = (isset($_POST[‘last_name’])) ? trim($_POST[‘last_name’]) : ‘’;
$email = (isset($_POST[‘email’])) ? trim($_POST[‘email’]) : ‘’;
$city = (isset($_POST[‘city’])) ? trim($_POST[‘city’]) : ‘’;
$state = (isset($_POST[‘state’])) ? trim($_POST[‘state’]) : ‘’;
$hobbies = (isset($_POST[‘hobbies’]) & & is_array($_POST[‘hobbies’])) ?
Trang 10// check if username already is registered
$query = ‘SELECT username FROM site_user WHERE username = “’
foreach ($errors as $error) {
echo ‘ < li > ’ $error ‘ < /li >
$query = ‘INSERT INTO site_user
(user_id, username, password)
VALUES
(NULL, “’ mysql_real_escape_string($username, $db) ‘”, ‘
‘PASSWORD(“’ mysql_real_escape_string($password,
$db) ‘”))’;
Trang 11$result = mysql_query($query, $db) or die(mysql_error());
$user_id = mysql_insert_id($db);
$query = ‘INSERT INTO site_user_info (user_id, first_name, last_name, email, city, state, hobbies) VALUES
(‘ $user_id ‘, ‘ ‘”’ mysql_real_escape_string($first_name, $db) ‘”, ‘ ‘”’ mysql_real_escape_string($last_name, $db) ‘”, ‘ ‘”’ mysql_real_escape_string($email, $db) ‘”, ‘ ‘”’ mysql_real_escape_string($city, $db) ‘”, ‘ ‘”’ mysql_real_escape_string($state, $db) ‘”, ‘ ‘”’ mysql_real_escape_string(join(‘, ‘, $hobbies), $db) ‘”)’;
$result = mysql_query($query, $db) or die(mysql_error());
$_SESSION[‘logged’] = 1;
$_SESSION[‘username’] = $username;
header(‘Refresh: 5; URL=main.php’);
< > < strong > Thank you < ?php echo $username; ? > for registering! < /strong > < /p >
< > Your registration is complete! You are being sent to the page yourequested If your browser doesn’t redirect properly after 5 seconds,
< a href=”main.php” > click here < /a > < /p >
/body >
< /html >
< ?php die();
}}
< td > < label for=”username” > Username: < /label > < /td >
< td > < input type=”text” name=”username” id=”username” size=”20”
maxlength=”20” value=” < ?php echo $username; ? > ”/ > < /td >
< /tr > < tr >
< td > < label for=”password” > Password: < /label > < /td >
< td > < input type=”password” name=”password” id=”password” size=”20”
Trang 12maxlength=”20” value=” < ?php echo $password; ? > ”/ > < /td >
< /tr > < tr >
< td > < label for=”email” > Email: < /label > < /td >
< td > < input type=”text” name=”email” id=”email” size=”20” maxlength=”50”
value=” < ?php echo $email; ? > ”/ > < /td >
< /tr > < tr >
< td > < label for=”first_name” > First name: < /label > < /td >
< td > < input type=”text” name=”first_name” id=”first_name” size=”20”
maxlength=”20” value=” < ?php echo $first_name; ? > ”/ > < /td >
< /tr > < tr >
< td > < label for=”last_name” > Last name: < /label > < /td >
< td > < input type=”text” name=”last_name” id=”last_name” size=”20”
maxlength=”20” value=” < ?php echo $last_name; ? > ”/ > < /td >
< /tr > < tr >
< td > < label for=”city” > City: < /label > < /td >
< td > < input type=”text” name=”city” id=”city” size=”20” maxlength=”20”
value=” < ?php echo $city; ? > ”/ > < /td >
< /tr > < tr >
< td > < label for=”state” > State: < /label > < /td >
< td > < input type=”text” name=”state” id=”state” size=”2” maxlength=”2”
value=” < ?php echo $state; ? > ”/ > < /td >
< /tr > < tr >
< td > < label for=”hobbies” > Hobbies/Interests: < /label > < /td >
< td > < select name=”hobbies[]” id=”hobbies” multiple=”multiple” >
The register.php script is the whole core of your registration system in one file: registration form,
error handling, and placing the data into the database The page allows users to enter different
information for their accounts, and restricts users from using someone else ’ s username for registration
Once users are registered, you can allow them to log in to the system and modify their account
information as they see fit
The main.php page checks whether or not a user is logged in Again, the $ _SESSION[ ‘ user_
logged ’ ] variable is being checked to see if users have already been logged in and are just revisiting
some pages They are shown different page content, depending on whether they are logged in or not
Trang 13Here ’ s a quick recap of what you ’ ve done:
❑ You have an index page that checks whether or not a user is logged in
❑ Based on that check, it either shows the user directions to log in or to register, to allow access to his
or her personal information area
❑ You have the registration area covered, along with the login process, and are keeping users tracked
with their session information
Try It Out Authorizing Users to Edit Their Accounts
You will create the area where users are allowed to change their information or delete their account, but first you will need to slightly modify the authorization page, which checks whether or not users are logged in and redirects them accordingly You also need to make some slight modifications to the login page:
1 Modify auth.inc.php with the highlighted changes:
< ?php// start or continue sessionsession_start();
if (!isset($_SESSION[‘logged’])) { header(‘Refresh: 5; URL=login.php?redirect=’ $_SERVER[‘PHP_SELF’]);
echo ‘ < > You will be redirected to the login page in 5 seconds < /p >
echo ‘ < > If your browser doesn\’t redirect you properly automatically, ‘ ‘ < a href=”login.php?redirect=’ $_SERVER[‘PHP_SELF’]
include ‘db.inc.php’;
$username = (isset($_POST[‘username’])) ? trim($_POST[‘username’]) : ‘’;
$password = (isset($_POST[‘password’])) ? $_POST[‘password’] : ‘’;
Trang 14$redirect = (isset($_REQUEST[‘redirect’])) ? $_REQUEST[‘redirect’] :
‘main.php’;
if (isset($_POST[‘submit’])) {
$query = ‘SELECT username FROM site_user WHERE ‘
‘username = “’ mysql_real_escape_string($username, $db) ‘” AND ‘
‘password = PASSWORD(“’ mysql_real_escape_string($password,
header (‘Refresh: 5; URL=’ $redirect);
echo ‘ < > You will be redirected to your original page request < /p >
echo ‘ < > If your browser doesn\’t redirect you properly
automatically, ‘
‘ < a href=”’ $redirect ‘” > click here < /a > < /p >
die();
} else {
$error = ‘ < > < strong > You have supplied an invalid username and/or ‘
‘password! < /strong > Please < a href=”register.php” > click here ‘
‘to register < /a > if you have not done so already < /p >
< td > < input type=”text” name=”username” maxlength=”20” size=”20”
value=” < ?php echo $username; ? > ”/ > < /td >
< /tr > < tr >
< td > Password: < /td >
< td > < input type=”password” name=”password” maxlength=”20” size=”20”
value=” < ?php echo $password; ? > ”/ > < /td >
< /tr > < tr >
< td > < /td >
< td >
< input type=”hidden” name=”redirect” value=” < ?php echo $redirect ? > ”/ >
< input type=”submit” name=”submit” value=”Login”/ >
Trang 153 Create the user_personal.php page with the following code:
< ?phpinclude ‘auth.inc.php’;
< h1 > Welcome to your personal information area < /h1 >
< > Here you can update your personal information, or delete your account < /p >
< > Your information as you currently have it is shown below < /p >
< > < a href=”main.php” > Click here < /a > to return to the home page < /p >
< ?php
$query = ‘SELECT username, first_name, last_name, city, state, email, hobbies FROM
site_user u JOIN site_user_info i ON u.user_id = i.user_id WHERE
username = “’ mysql_real_escape_string($_SESSION [‘username’], $db) ‘”’;
$result = mysql_query($query, $db) or die(mysql_error($db));
< li > First Name: < ?php echo $first_name; ? > < /li >
< li > Last Name: < ?php echo $last_name; ? > < /li >
< li > City: < ?php echo $city; ? > < /li >
< li > State: < ?php echo $state; ? > < /li >
< li > Email: < ?php echo $email; ? > < /li >
< li > Hobbies/Interests: < ?php echo $hobbies; ? > < /li >