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

PHP & MySQL Everyday Apps for Dummies phần 3 docx

45 295 0

Đ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

Định dạng
Số trang 45
Dung lượng 789,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

If the Web page displays any informa-tion stored in PHP variables, an array of the data to be displayed in the Webpage must also be passed.The propertiesThe WebPageproperties store the i

Trang 1

Writing the WebPage classThe WebPageclass is used frequently throughout this book whenever a Webpage needs to be displayed The WebPageclass has a single function: to dis-play a Web page The class expects the name of a file that contains the codethat defines the Web page to be passed If the Web page displays any informa-tion stored in PHP variables, an array of the data to be displayed in the Webpage must also be passed.

The propertiesThe WebPageproperties store the information needed to display the Web page

private $filename;

private $data;

$filenameis the name of the file that contains the code that defines the Webpage — HTML code and perhaps some PHP code for parts of the Web pagethat use PHP variables The file that defines the Web page for the authentica-tion application presented in this chapter is named Welcome.inc The samefile is used for the procedural code and is shown in Listing 3-2

$datais an array that contains the PHP variables for the Web page If mation contained in PHP variables is displayed on the page, the PHP vari-ables must be passed in an array If no PHP variables are displayed, $datacan be NULL

infor-The codeListing 3-6 contains the complete code for the WebPageclass The construc-tor and the single displayPagemethod are discussed in detail after the codelisting Notice the line numbers at the ends of some of the lines of code Thediscussion following the listing refers to the line numbers

L ISTING 3-6: T HE C ODE FOR THE W EB P AGE C LASS

<?php /* Class: WebPage

* Desc: Class that stores the information needed to

* display a Web page.

*/

class WebPage {

private $filename;

private $data;

function _ _construct($filename,$data=NULL) #11

Trang 2

The constructorWhen a WebPageobject is instantiated, the filename and the data that arepassed to the constructor are stored in the properties.

#11 The constructor definition includes a default value for $data: NULL If

no value is passed for data, NULLis stored in the $dataproperty Thisgives the object the flexibility to store and display Web pages that areonly HTML as well as Web pages that contain PHP variables

#13 Begins an if/elsestatement that tests whether the filename passed

is a string If it’s a string, it’s stored in a property If it’s not a string,the elseblock executes, which throws an exception and exits

#21 Begins an if/elsestatement that tests whether the data passed is in

an array The ifstatement executes if the data is NULLor is an arrayand stores the data passed to the constructor in the $dataproperty.The elseblock that begins on line 26 executes when the data is notpassed in an array A new exception is thrown with a message, andthe program exits

in an array”);

} }

function displayPage() {

} }

?>

Trang 3

displayPageThis method displays the Web page based on the information stored in theproperties

#34 Extracts the PHP variables for the $dataarray If no PHP variables areused in the Web page, no data was passed, and $datais NULL To pre-vent a notice from being displayed when $datais NULL, an @is usedbefore the extract function

#35 Includes a file that defines the Web page based on the filename stored

in the $filenameproperty

Using the WebPage class

A WebPageobject is created with a statement similar to one of the following:

$page1 = new WebPage(“Welcome.inc”);

$page2 = new WebPage(“Welcome.inc”,$data);

You can use the first statement to create a WebPageobject when the Webpage contains only HTML code and no PHP variables The second statementcreates an object that contains PHP variables to display in the Web page

When the second parameter is passed, it must be an array If a second ter is included that is not an array (for instance, just a string or an integer), anexception is thrown with the following message:

parame-Data must be passed in an array

Writing the Auth-OO scriptThe application script creates and uses the objects to provide the applica-tion’s functionality For the HTTP authentication application, the script mustprompt the user to enter a user name and password and then check whetherthe user name and password are valid Listing 3-7 shows the applicationscript Auth-OO.php

The flow of the application script is controlled by an ifstatement that testswhether a user name and password have been entered, by testing whetherthe $_SERVERarray contains the user name The following is the generaldesign of the application script:

if (user name and password have not been submitted)

Prompt the user to enter a user name and password

else (user name and password have been submitted)

1 Test whether user name and password match a user name and password in the valid user database.

2 If user name and password are valid, display the

Trang 4

content of the protected Web page

3 If user name and/or password are not valid, prompt the user again for login information.

L ISTING 3-7: T HE A PPLICATION S CRIPT T HAT C REATES AND U SES O BJECTS

<?php /* Program: Auth-OO.php

* Desc: Program that prompts for a user name and password

* from the user using HTTP authentication The

* program then tests whether the user name and

* password match a user name and password pair

* stored in a MySQL database.

$prompter = new PasswordPrompter(“secret section”);

$prompter->displayPrompt();

} catch(Exception $e) {

echo $e->getMessage();

exit();

} }

// Testing the user name and password entered by the user

Trang 5

The application program has a single if/elsestatement to prompt for andtest a user name/password pair If the user has not submitted login informa-tion, the script prompts for a user name and password When the user sub-mits the login information, the user name and password are compared to thevalid user accounts stored in the MySQL database If the information is valid,the contents of the Web page are sent to the user (The following discussionrefers to line numbers in Listing 3-7.)

#10 Lines 10 to 13 include the files that contain the classes needed for theapplication require_onceis used so that the class is not acciden-tally included more than once

#16 Begins an ifblock that executes if the user has not submitted a username If $_SERVER[‘PHP_AUTH_USER’]isn’t set, the user hasn’t sub-mitted a password, so a PasswordPrompterobject is created and dis-played, resulting in a window that prompts for a user name andpassword

if(!$acct->selectAccount($_SERVER[‘PHP_AUTH_USER’])) {

echo $e->getMessage();

exit();

}

?>

Trang 6

#31 Begins an elseblock that executes when the user enters login mation in the HTTP password window The user name and passwordsubmitted by the user are available to the script in the $_SERVERsuperglobal array in the elements PHP_AUTH_USERand PHP_AUTH_PW.

infor-#35 Creates a Databaseobject

#36 Selects the database that contains the user account tion If useDatabasefails (returns FALSE) because

informa-“UserAccount”doesn’t exist, a message is displayed, and thescripts stops

#45 Lines 45 and 46 create an Accountobject

#47 Begins an ifblock that selects the account based on the username submitted by the user If selectAccountfails (returnsFALSE) because the user name isn’t found in the database, amessage is displayed, and the scripts stops

#52 Ends the ifblock that selects the account

#53 Begins an ifblock that compares the password submitted bythe user with the password stored in the database If the pass-words don’t match (the method returns FALSE), a message isdisplayed, and the script exits

#58 End of the ifblock the compares the passwords

#65 End of the elseblock that tests the user login informationagainst the valid login information in the database The scriptgoes past this line only if the login information submitted bythe user is valid

#66 Creates an array of data to be displayed on the Web page The arraycontains only one element: user_name

#69 Creates a new WebPageobject containing the welcome Web page Thefilename passed to the WebPageobject is Welcome.inc This is thesame file that is used for the procedural script shown previously inListing 3-2

#70 Displays the welcome WebPage The Web page that is displayed is thesame welcome page displayed by the procedural script (refer toFigure 3-3)

Notice that many of the lines in the script are in tryblocks Methods that canthrow an exception should be in tryblocks If an object method throws anexception that you don’t catch, you get a fatal error similar to the following:

Fatal error: Uncaught exception ‘Exception’ with message

‘Database is not available.’ in c:\Database.class:18

Trang 7

Chapter 4

User Login Application

In This Chapter

Designing the login Web page

Building the database to store user information

Writing procedural code for the login application

Developing and using objects to program the login application

Many Web sites are secret or have secret sections Such Web sites require

users to log in before they can see the secret information Here are atwo examples of when Web sites might restrict access:

 Many online merchants require customers to log in so that their tion can be stored for future transactions These companies must pro-tect the customers’ information, particularly financial information, frompublic view

informa- Many Web sites grant access only to certain people For example, pany information might be restricted to company staff or members of acertain department Another example is when information is availablefor sale, so the information must be restricted to people who have paidfor it

com-If you have a Web site that needs protection, be sure to implement a user

login application User login applications can be quite simple, such as an

application in which the administrator sets up a list of valid users Anyonewho tries to access a protected file is prompted to enter a user name andpassword that is checked against the list of valid users A login applicationcan also be much more complicated It can allow Web site visitors to registerfor access, setting up their own accounts The application might collect infor-mation from customers as they register The application might provide theability for users to manage their own accounts The features that a loginapplication can provide are wide and varied

A user login application is one of the most common applications on the Web,

so I’m sure you’ve had the experience of logging in to one In this chapter, Ishow you how to build your own user login application

Trang 8

If you need only a simple login screen, the application that I provide inChapter 3 might be sufficient for your needs; it uses the built-in HTTP authen-tication features of browsers The login application in this chapter is morecomplex It allows users to register or to log in if they’re already registeredand collects and stores information from users when they register It provides

a fairly complex login Web page with two forms: one for login and one for istration If you need to provide this additional functionality and control thelook and feel of your login application, this chapter is for you

reg-Designing the Login Application

The basic function of the login application is to allow registered users toenter the Web site and to block access to users who have not registered The application also allows users to register, storing their information in

a database To meet this functionality, the user login application should

 Validate the information submitted in the form

Make sure the required fields are not blank and the submitted tion is in the correct format

informa- Store the validated information in the database

 Display a login form that asks for the registered customer’s user nameand password

 Compare the user name and password that a user enters with the usernames and passwords in the database If a match is found, send a Webpage from the site to the customer If no match is found, give the cus-tomer the opportunity to try to log in again

Creating the User Database

The application design calls for a database that stores user information Thedatabase is the core of this application A login application must store usernames and passwords, at the very least, but often you’ll want to store addi-tional information as well

Trang 9

Designing the databaseYour first design task is to decide what information you want to store At aminimum, you need to store a user name and password that the user can use

to log in It’s also useful to know when the user account was created In ing what information to collect during user registration, you need to balanceyour urge to collect all the potentially useful information that you can think

decid-of against your users’ urge to avoid time-consuming forms and reluctance togive out personal information One compromise is to ask for some optionalinformation; users who don’t mind will enter it, and those who object can justleave it blank

Some information is required for your Web site to perform its function Forinstance, users can readily see that a site that will be sending them somethingneeds to collect their names and addresses However, they might not see why it’s necessary for you to have their phone numbers Even if you require aphone number, users sometimes enter fake ones So unless you have a captiveaudience, such as your employees, who must give you everything you ask for,think carefully about what information to collect It’s easy for irritated users toleave your Web site It’s not like they drove miles to your store and lookedhours for a parking space They can leave with just a click

For the sample application in this chapter, the Web site is an online store thatsells products Thus, you need to collect the customers’ contact information,and you need their phone numbers in case you need to contact them abouttheir orders Most customers are willing to provide phone numbers to rep-utable online retailers, recognizing that problems with an order might neces-sitate the merchant contacting them The remainder of this section discussesthe details of the information and its storage in a MySQL database

The database contains only one table The customer information is stored in

the table, one record (row) for each customer The fields needed for the table

are shown in Table 4-1 The table contains 12 fields The first three fields,user_name, password, and create_date, are required and cannot be blank

The remaining fields contain the customer’s name, address, phone number,and fax number and are allowed to be blank The first field, user_name, is theprimary key

Table 4-1 Database Table: Customer

Variable Name Type Description

user_name VARCHAR(20) User name for the user

account (primary key)create_date DATE Date when the account was

added to the table

(continued)

Trang 10

Table 4-1 (continued)

Variable Name Type Description

password VARCHAR(255) Password for the accountemail VARCHAR(50) Customer’s e-mail addresslast_name VARCHAR(50) Customer’s last namefirst_name VARCHAR(40) Customer’s first namestreet VARCHAR(50) Customer’s street addresscity VARCHAR(50) City where customer livesstate CHAR(2) Two-letter state codezip CHAR(10) Zip code, five numbers or zip + 4phone CHAR(15) Phone number where customer

can be reachedfax CHAR(15) Customer’s fax number

Building the databaseYou can create the MySQL database with the following SQL statement:

CREATE DATABASE CustomerDirectory;

The following SQL statement creates the table:

CREATE TABLE Customer ( user_name VARCHAR(20) NOT NULL, create_date DATE NOT NULL, password VARCHAR(255) NOT NULL, last_name VARCHAR(50),

first_name VARCHAR(40), street VARCHAR(50), city VARCHAR(50), state CHAR(2), zip CHAR(10), email VARCHAR(50), phone CHAR(15), fax CHAR(15), PRIMARY KEY(user_name) );

Trang 11

Accessing the databasePHP provides MySQL functions for accessing your database from your PHPscript The MySQL functions are passed the information that’s needed toaccess the database, such as a MySQL account name and password This isnot related to any other account name or password that you have, such as apassword to log in to the system.

Several new features became available with MySQL 4.1 To access the newfeatures, you must use the mysqli functions, rather than the mysql functions

To use the mysqli functions, you must use PHP 5 The mysqli functions arenot available with PHP 4 You can still use the mysql functions and PHP 4 tointeract with MySQL 4.1, but you can’t use some of the new features Themysqli functions are very similar to the mysql functions, but some differ-ences exist Read about MySQL and PHP versions in Chapter 1 Read aboutmysql/mysqli functions in Appendix C Read about the mysqli (MySQLImproved) module at www.php.net/manual/en/ref.mysqli.php

In this application, I have stored the information needed by the PHP mysqlfunctions in a separate file called Vars.inc This file is stored in a directoryoutside my Web space, for security reasons The file contains informationsimilar to the following:

Adding data to the databaseThis database is intended to hold data entered by customers — not by you

When the application is first made available to customers, it’s empty untilcustomers add data When you test your application programs, the scriptsadd a row to the database You might want to add a row with a user name andpassword for your own use when testing the scripts

Trang 12

Building the Login Web Page

Customers log in to your protected Web site via an HTML form on a Webpage The login application design, developed earlier in this chapter, calls fortwo forms: one form to allow new customers to register and another form toallow registered customers to log in You need to develop the login Web page,making decisions on its functionality and its look and feel

Designing the login Web page

In your Web travels, you’ve probably seen many different designs for loginpages You might already have ideas for your login page The design pre-sented here is not the only possible one, just one I like Feel free to changeany part of it

In this design, both forms are presented on a single Web page The forms aredisplayed in two sections, side by side Each form has its own section head-ing, form fields, and submit button The login form allows people to entertheir user names and passwords; the registration form requests much moreinformation from customers Figure 4-1 shows what the login Web page lookslike when it’s displayed in a browser

Figure 4-1:

The loginWeb pagedisplayed

by the user loginapplication

Trang 13

The code for the login Web page is the same whether you’re using the dural approach or the object-oriented approach to build your application.

proce-The code for the login Web page is stored in separate files that are includedwhen the application needs to display the login page Thus, the code thatdefines the Web page is separate from the PHP code that provides the logic

of the application

The code for the login page consists of two files: the code that defines thelook and feel of the page and the code that provides the specific informationfor the page

Writing the code for the login pageThe login Web page provides two forms: a login form and a registration form, side by side The code that creates the page is in two separate files,

as follows:

double_form.inc: Contains the code that defines the look and feel ofthe Web page It produces a Web page with two side-by-side forms andcan be used to create any Web page that needs two side-by-side forms

This file does not include specific information, such as the names andvalues of the text fields displayed in the forms You must use another file

in conjunction with this file to create the Web page The other file tains the specific information, such as field names, for the Web page

con-fields_login.inc: Contains the specific information for the login Webpage When used with double_form.inc, it displays a customer loginWeb page A different file with different fields can be used with double_

form.incto create a Web page that displays forms with fields unrelated

to customer logins

The remainder of this section shows the details of these files The second file is short and easier to understand, so I discuss it first in Listing 4-1 Thenwhen explaining the first file (double_form.inc) in Listing 4-2, I refer to theinformation contained in fields_login.inc

Writing fields_login.incThe file shown in Listing 4-1 provides seven arrays that contain the specificinformation displayed in the login Web page The arrays are as follows:

$page: Elements that are displayed at the top and bottom of the page

These elements span the entire page, not just one of the forms

$elements_1: Elements that are displayed at the top and bottom of thefirst form (the form on the left) This array contains text to display at thetop and bottom of the form and the text to display on the submit button

Trang 14

$elements_2: Similar elements for the second form (the form on theright).

$fields_1: The names and labels for the fields to be displayed in thefirst form The array keys are the field names in the form and the arrayvalues are the labels that are displayed in the form next to the fields

$length_1: The lengths of the fields in the first form It’s not necessary

to define lengths for the fields, but you can if you want For example, youcan make all the fields the same length I prefer to define lengths forfields as a security measure; it restricts the number of characters that auser can type into a field, limiting some of the opportunities for a badguy to enter evil things into your forms

$fields_2: The names and labels for the fields in the second form Thearray keys are the field names Because these fields are stored in the data-base, the array keys are the same names used in the database table Thearray values are the labels that are displayed in the form next to the fields.For instance, the field name used in the database is first_name, but the

label in the form is much clearer and more attractive as First Name.

$length_2: The lengths of the fields in the second form The length ofthe fields is the same as the length of the fields defined in the database.Setting up your elements and fields in this separate file, rather than includingthem in the file with the HTML code for the form, greatly simplifies the designand maintenance of the form You can easily see the fields and elements inthis separate file, as well as easily edit and modify them

L ISTING 4-1: T HE F ILE T HAT C ONTAINS THE A RRAYS N EEDED FOR THE L OGIN P AGE

<?php /* File: fields_login.inc

* Desc: Contains arrays with the field names and form

* elements for the login Web page The arrays named

* with l are displayed in form 1 and those named

* with 2 are displayed in form 2 The forms are

* defined in the file double_form.inc

$elements_1 = array( “top” => “Returning Customers:

<span style=\”font-size: 80%; font-weight: 100%\”>

<i>Login here</i></span>”,

“bottom” => “”,

“submit” => “Login”

Trang 15

Notice that the arrays are defined in a structured format You could use muchless space to define the arrays, but this format makes the values clear andeasy to change if necessary.

Notice that some of the values are blank, such as $element_1[“bottom”]=””

In this particular Web page, I didn’t want to include any text at the top of thepage or at the bottom of the forms However, for another form using double_

form.inc, you might want to include values for these elements

);

$elements_2 = array(“top” => “New Customers:

<span style=\”font-size: 80%; font-weight: 100%\”>

“email” => “Email Address”,

“first_name” => “First Name”,

“last_name” => “Last Name”,

Trang 16

Writing double_form.incThe script double_form.inc, shown in Listing 4-2, contains the code thatdefines how the Web page looks It includes HTML code for the forms and fortables to organize the page The code includes variables where specific infor-mation is needed The variable values are provided in the previous file,fields_login.inc For example, the script includes the following line thatdefines the Web page title:

<head><title><?php echo $page[‘title’]?></title></head>

The variable $page[‘title’]is found in the file fields_login.inc, where

it is set to “Customer Login Page”

L ISTING 4-2: T HE S CRIPT T HAT D EFINES T WO S IDE - BY -S IDE HTML F ORMS

<?php /* File: double_form.inc

* Desc: Contains the code for a Web page that displays

* two HTML forms, side by side in a table.

<! Beginning of form 1 (left) >

<form action=<?php echo $_SERVER[‘PHP_SELF’]?>

Trang 17

<input type=”submit” name=”Button”

value=”<?php echo $elements_1[‘submit’]?>”>

<! Beginning of Form 1 (right side) >

<form action=<?php echo $_SERVER[‘PHP_SELF’]?>

Trang 18

The following numbers refer to the line numbers in Listing 4-2:

#6 Includes a file containing functions used in this script The file functions.incis shown in Listing 4-3

echo “>$state\n”;

} echo “</select>”;

else { if(ereg(“pass”,$field))

<input type=”submit” name=”Button”

value=”<?php echo $elements_2[‘submit’]?>”>

Trang 19

#8 Lines 8 to 12 are an HTML section The HTML code defines the top ofthe Web page Lines 8 and 10 have a small PHP section that echoes avariable The variable values are found in the fields_login.incfile.

Line 12 begins the table that organizes the Web page

#18 Lines 18 to 25 contain HTML code that opens the first table cell, plays the text at the top of the cell, and produces the form tag Asecond table, inside this first cell, is started to hold the form fields

dis-#26 Opens the PHP section that produces the form fields

#27 Begins an ifblock that displays a message If the item “message_1”

exists in the GLOBALSarray, message_1is displayed The message isset into the global array in the application script when errors arefound in the information entered by the user If the form is displayedfor the first time, before the user enters anything, or if no errorsoccur, the GLOBALSelement message_1doesn’t exist

#36 Lines 36 to 49 contain a foreachblock that displays all the fields inthe form The foreachstatement walks through the $fields_1arraythat is set in the file fields_login.inc

#38 Starts an ifstatement that sets a value for $type— a variableused in the input field code The input field is type textfor allfields except the password field, which is type password

#42 Lines 42 to 48 contain the echostatement that outputs theHTML code for the field The echostatement is executed oncefor each element in the $fields_1array PHP variables areused for the specific information, such as field names, in thestatement

#51 Starts an HTML section (lines 51 to 59) that displays the submitbutton for form 1 and closes the tags for form 1

#62 HTML code that displays a column that separates the two forms

#67 An HTML section (lines 67 to 75) that opens the second table cell, displays the text at the top of the cell, and produces the form tag

A second table, inside this second cell, is started to hold the formfields

#76 Opens the PHP section that produces the form fields

#77 Begins an ifblock that displays a message If the item “message_2”

exists in the GLOBALSarray, message_2is displayed The message

is set into the global array in the application script when errors arefound in the information entered by the user If the form is displayedfor the first time, before the user enters anything, or if no errorsoccur, the GLOBALSelement message_2doesn’t exist

#85 Lines 85 to 119 contain a foreachblock that displays all the fields inthe form The foreachstatement walks through the $fields_2arraythat is set in the file fields_login.inc

Trang 20

#87 Starts an ifblock that executes only for the statefield Adrop-down list of states is displayed rather than the simple textfield that is displayed for all the other fields Lines 96 to 97 usethe functions included on line 6.

#105 Starts an elseblock that executes for all fields except thestatefield

#107 Starts an ifstatement that sets a value for $type— a variableused in the input field code The input field is type textfor allfields except the password field, which is type password

#111 Lines 111 to 117 contain the echostatement that outputs theHTML code for the field The echostatement is executed oncefor each element in the $fields_2array PHP variables areused for the specific information, such as field names, in thestatement

#121 Starts an HTML section that displays the submit button for form 2,

closes the tags for form 2, and displays the page text at the bottom ofthe Web page

In double_form.inc, the statefield in form 2 is a drop-down list The codethat creates the list uses two functions stored in the functions.incfilethat’s included on line 6 Listing 4-3 shows the code for the two functions

L ISTING 4-3: F UNCTIONS T HAT C REATE A RRAYS OF S TATE N AMES AND C ODES

<?php function getStateCode() {

$stateCode = array(1=> “AL” ,

“AK” ,

“AZ” ,

“WY” );

return $stateCode;

}

function getStateName() {

$stateName = array(1=> “Alabama”,

“Alaska”,

“Arizona”, .

“Wyoming” );

return $stateName;

}

?>

Trang 21

The functions are called on lines 92 and 93 of Listing 4-2 The arrays created

by these functions are used to create the drop-down list of states in the forstatement that starts on line 94 of Listing 4-2

Displaying the login Web pageThe file double_form.incis used in conjunction with fields_login.inctodisplay the login Web page Although the approach to displaying the formmight be different in the procedural script versus the object-oriented script,the code that displays the form is the same, as follows:

in the input tags must be available

When the customer submits the form, the information the user typed ispassed to the script in the $_POSTsuperglobal array If you redisplay theform, you can get the information from this array to display in the form byusing the PHP extractfunction, as follows:

Building the Login Application:

The Procedural Approach

The login application has one main script that’s organized into three basicsections:

 A section that executes the first time the login page is displayed, beforethe user clicks a button

Trang 22

 A second section that executes when the user clicks the Login button

 A third section that executes when the user clicks the Register button

A switchstatement controls the program flow based on which button isclicked The following is an overview of the script’s structure:

3 When information is correct, store it in database.

4 When registration succeeds, display the protected Web page.

case “default”:

Display the Login Web Page with blank form fields.

The default case executes if neither the Login button nor the Register button

* Desc: Main application script for the User Login

* application It provides two options: (1) login

* using an existing User Name and (2) register

* a new user name User Names and passwords are

* stored in a MySQL database

*/

Ngày đăng: 12/08/2014, 21:21

TỪ KHÓA LIÊN QUAN