1. Trang chủ
  2. » Công Nghệ Thông Tin

Beginning PHP6, Apache, MySQL Web Development- P15 docx

30 418 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Beginning PHP6, Apache, MySQL Web Development
Trường học Not specified
Chuyên ngành Web Development
Thể loại Textbook chapter
Năm xuất bản 2008
Định dạng
Số trang 30
Dung lượng 528,08 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Remember that cookie information is exchanged within HTTP headers; cookies must be sent before the script generates any output.. In addition to the information it stores, each cookie has

Trang 1

You can then navigate to cookies_view.php This page checks to see if the cookie values are valid If they are not, it says “ No cookies are set, ” and you can try to set the cookies again If the cookies were set successfully, then the screen will look like the one in Figure 12 - 17

The Set Cookies link directs you to cookies_set.php , which does just what the name says: It sets cookie variables named username and remember_me , which are just hard - coded in this example It then uses a header redirect to send you back to the main test page Figure 12 - 16 shows cookies_set.php in action

Figure 12-16

Trang 2

Try closing out your browser and then reopening it to visit cookies_view.php again You ’ ll see that

the cookies are still active

The cookies are set to expire 30 days from when they were set If you want to delete them, you can

visit the Delete Cookies link It calls cookies_delete.php , which expires the cookies by setting their

expiration date in the past and blanking out their values

Remember that cookie information is exchanged within HTTP headers; cookies must be sent before the

script generates any output

If you look at the documentation for the setcookie() function, you will see that it can accept more

arguments than what we ’ ve given it in this simple test In addition to the information it stores, each

cookie has a set of attributes: an expiration date, a valid domain, a valid domain path, and an optional

security flag These attributes help ensure that the browser sends the correct cookie when a request is

made to a server

The expiration time is used by the browser to determine when the cookie should be deleted It is

expressed as a UNIX timestamp plus the number of seconds before the cookie expires

Figure 12-17

Trang 3

The valid domain is a partial or complete domain name to which the cookie will be sent For example,

if the value for the valid domain attribute is www.example.net , the client will send the cookie information every time the user visits the www.example.net subdomain For the cookie to be accessible within all subdomains of example.net (such as www.example.net , mail.example.net , news

example.net , users.example.net , etc.), a leading dot should be used, as in example.net The path attribute is used to identify sites within various paths in the same domain For example, cookies with a path attribute of / will be accessible to both users.example.net/~joe and users.example.net/~sally However, a cookie with a path attribute of /~tom will only be made available

to users.example.net/~tom , not users.example.net/~sally This is good to keep in mind if your site is on a shared server with the same domain name as other sites

The security flag attribute restricts a browser from sending cookie information over unsecured connections The default value is 0 and allows the cookie to be sent over any type of HTTP connection It may be set to 1, which will only permit the cookie to be sent over a secure HTTP (HTTPS) connection that utilizes SSL (Secure Socket Layer)

Now that you have some cookie knowledge, you can use it in the login system if you want When written and set appropriately, a cookie will only be sent to the appropriate web site However, cookie information is still stored on the user ’ s computer in a plaintext format and can be viewed by anyone with access to the local machine Never use cookies to store sensitive information such as passwords and credit card information, and make sure that any major operation (such as changing a user ’ s preferences

or submitting/accessing credit card details) requires the user to enter his or her full password

Administrator Registration

In this last portion of the chapter, you learn how logged - in admins can change information and delete information based on their access privileges In this section, administrators are required to log in before they can view the users signed up in the user registration database Once they are logged in, only certain privileged admins will be allowed to perform certain operations For this example:

Users with an admin privilege level of 0 are regular users

Users with an admin privilege level of 2 are allowed to update other user accounts, but not delete them

Users with an admin privilege level of 1 are allowed to update and delete other user accounts This would be useful if a user was, for some reason, unable to log in to the site, and the administrator needed to reset passwords, change usernames, and so on — but you don ’ t want just any administrator to

be allowed to do everything the main administrator does

Trang 4

Try It Out Administration Section

First, enter the code for all of the pages that are in the following steps We will explain how they work

$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or

die (‘Unable to connect Check your connection parameters.’);

mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));

// update the user table

$query = ‘ALTER TABLE site_user

ADD COLUMN admin_level TINYINT UNSIGNED NOT NULL DEFAULT 0

AFTER password’;

mysql_query($query, $db) or die (mysql_error($db));

// give one of our test accounts administrative privileges

$query = ‘UPDATE site_user SET admin_level = 1 WHERE username = “john”’;

mysql_query($query, $db) or die (mysql_error($db));

echo ‘Success!’;

?

2 Load db_ch12 - 2.php in your browser, and you should see the success message

3 Modify login.php as shown:

$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or

die (‘Unable to connect Check your connection parameters.’);

mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));

// filter incoming values

$username = (isset($_POST[‘username’])) ? trim($_POST[‘username’]) : ‘’;

$password = (isset($_POST[‘password’])) ? $_POST[‘password’] : ‘’;

$redirect = (isset($_REQUEST[‘redirect’])) ? $_REQUEST[‘redirect’] :

Trang 5

$result = mysql_query($query, $db) or die(mysql_error($db));

if (mysql_num_rows($result) > 0) { $row = mysql_fetch_assoc($result);

$_SESSION[‘username’] = $username;

$_SESSION[‘logged’] = 1;

$_SESSION[‘admin_level’] = $row[‘admin_level’];

header (‘Refresh: 5; URL=’ $redirect);

echo ‘ < > You will be redirected to your original page request < /p >

automatically, ‘ ‘ < a href=”’ $redirect ‘” > click here < /a > < /p >

mysql_free_result($result);

mysql_close($db);

die();

} else { // set these explicitly just to make sure $_SESSION[‘username’] = ‘’;

$_SESSION[‘logged’] = 0;

$_SESSION[‘admin_level’] = 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 >

} mysql_free_result($result);

}

? < 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 >

< /tr > < tr >

< td > < /td >

< td >

Trang 6

< input type=”hidden” name=”redirect” value=” < ?php echo $redirect ? > ”/ >

< input type=”submit” name=”submit” value=”Login”/ >

< > You may now < a href=”user_personal.php” > click here < /a > to go to your

own personal information area and update or remove your information should

you wish to do so < /p >

you will have access to your personal area along with other user

information < /p >

< > If you have already registered, < a href=”login.php” > click

here < /a > to log in Or if you would like to create an account,

< a href=”register.php” > click here < /a > to register < /p >

< ?php

}

?

Trang 7

5 Create admin_area.php with the following code:

< ?phpinclude ‘auth.inc.php’;

if ($_SESSION[‘admin_level’] < 1) { header(‘Refresh: 5; URL=user_personal.php’);

echo ‘ < > < strong > < /strong > You are not authorized for this page < /strong > < /p >

If your browser ‘ ‘doesn\’t redirect you automatically, < a href=”main.php” > click ‘ ‘here < /a > < /p >

die();

} include ‘db.inc.php’;

/head >

body >

< h1 > Welcome to the Administration area < /h1 >

< > Here you can view and manage other users < /p >

< > < a href=”main.php” > Click here < /a > to return to the home page < /p >

< table style=”width:70%” >

< tr > < th > Username < /th > < th > First Name < /th > < th > Last Name < /th > < /tr >

< ?php

$query = ‘SELECT u.user_id, username, first_name, last_name FROM

site_user u JOIN site_user_info i ON u.user_id = i.user_id ORDER BY

Trang 8

$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or

die (‘Unable to connect Check your connection parameters.’);

if (isset($_POST[‘submit’]) & & $_POST[‘submit’] == ‘Update’) {

// filter incoming values

$username = (isset($_POST[‘username’])) ? trim($_POST[‘username’]) : ‘’;

$user_id = (isset($_POST[‘user_id’])) ? $_POST[‘user_id’] : ‘’;

$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’])) ?

$_POST[‘hobbies’] : array();

// delete user record

Trang 9

if (isset($_POST[‘delete’])) { $query = ‘DELETE FROM site_user_info WHERE user_id = ‘ $user_id;

mysql_query($query, $db) or die(mysql_error());

$query = ‘DELETE FROM site_user WHERE user_id = ‘ $user_id;

< > < strong > The account has been deleted < /strong > < /p >

< > < a href=”admin_area.php” > Click here < /a > to return to the admin area < /a > < /p >

/body >

< /html >

< ?php die();

} $errors = array();

if (empty($username)) { $errors[] = ‘Username cannot be blank.’;

} // check if username already is registered $query = ‘SELECT username FROM site_user WHERE username = “’ $username ‘” AND user_id != ‘ $user_id;

$result = mysql_query($query, $db) or die(mysql_error());

if (mysql_num_rows($result) > 0) { $errors[] = ‘Username ‘ $username ‘ is already registered.’;

$username = ‘’;

} mysql_free_result($result);

if (empty($first_name)) { $errors[] = ‘First name cannot be blank.’;

}

if (empty($last_name)) { $errors[] = ‘Last name cannot be blank.’;

}

if (empty($email)) { $errors[] = ‘Email address cannot be blank.’;

}

if (count($errors) > 0) { echo ‘ < > < strong style=”color:#FF000;” > Unable to update the ‘ ‘account information < /strong > < /p >

echo ‘ < > Please fix the following: < /p >

echo ‘ < ul >

Trang 10

foreach ($errors as $error) {

echo ‘ < li > ’ $error ‘ < /li >

< > < strong > The account information has been updated < /strong > < /p >

< > < a href=”admin_area.php” > Click here < /a > to return to the

Trang 11

username, first_name, last_name, email, city, state, hobbies

AS my_hobbies FROM

site_user u JOIN site_user_info i ON u.user_id = i.user_id WHERE

u.user_id = ‘ $user_id;

$result = mysql_query($query, $db) or die(mysql_error());

if (mysql_num_rows($result) == 0) {

header(‘Location: admin_area.php’);

die();

} $row = mysql_fetch_assoc($result);

extract($row);

$password = ‘’;

$hobbies = explode(‘, ‘, $my_hobbies);

mysql_free_result($result);

< script type=”text/javascript” >

window.onload = function() { document.getElementById(‘cancel’).onclick = goBack;

} function goBack() { history.go(-1);

} < /script >

/head >

body >

< h1 > Update Account Information < /h1 >

< form action=”update_user.php” method=”post” >

< table >

< tr >

< 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=”text” name=”password” id=”password” size=”20”

maxlength=”20” value=” < ?php echo $password ? > ”/ >

< small > (Leave blank if you’re not changing the password.) < /mall > < /td >

< /tr >

Trang 12

< 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” >

echo ‘ < td > < input type=”checkbox” id=”delete” name=”delete”/ > ’

‘ < label for=”delete” > Delete < /label > < /td >

< input type=”hidden” name=”user_id” value=” < ?php echo $user_id;? > ”/ >

< input type=”submit” name=”submit” value=”Update”/ >

< input type=”button” id=”cancel” value=”Cancel”/ >

Trang 13

How It Works

This whole section adds new functionality specifically for administrators only onto the existing code base The purpose of db_ch12 - 2.php is to add a new column to the site_user table that tracks the privilege level of each user It also explicitly sets privileges on your “ john ” user account, so you have a test scenario to work with

$query = ‘ALTER TABLE site_user ADD COLUMN admin_level TINYINT UNSIGNED NOT NULL DEFAULT 0 AFTER Password’;

mysql_query($query, $db) or die (mysql_error($db));

$query = ‘UPDATE site_user SET admin_level = 1 WHERE username = “john”’;

mysql_query($query, $db) or die (mysql_error($db));

You made changes to main.php so that when the user logs in to the application and views his or her home page, the user will see a link to the administrator portion of the site if he or she has the appropriate privilege level

if ($_SESSION[‘admin_level’] > 0) { echo ‘ < > < a href=”admin_area.php” > Click here < /a > to access your ‘ ‘administrator tools < /p >

}

The main.php page showing the administrator link looks like Figure 12 - 18

Trang 14

Clicking on the link to the administration section brings the user to the admin_area.php page, shown

in Figure 12 - 19 It presents a list of accounts registered in the system for the user to manage

Figure 12-19

Depending on what link the administrator chooses, and whether he or she has a high enough admin

level, the admin will be able to update or delete the user ’ s account This screen looks like Figure 12 - 20

Trang 15

Summar y

By now, you have a good understanding of the power of PHP and its session and cookie functions, along with MySQL and database - driven information With these two powerful programs, along with Apache, you have some great tools to further your web development skill set Just think about the possibilities you can explore with all you learned in this chapter:

You can supplement Apache ’ s configuration on a per - directory basis, and even restrict access to files/directories via htpasswd

You can use PHP to accomplish the same file restriction tasks as htpasswd , but with more control and functionality

You can store user and admin information in a database and make use of database - driven logins

❑Figure 12-20

Ngày đăng: 03/07/2014, 07:20

TỪ KHÓA LIÊN QUAN