Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 50 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
50
Dung lượng
1,41 MB
Nội dung
4 <input type="password" name="password">< br />
5 <input type="hidden" name="login">< br />
<input type="submit"> <input type="reset">
</form>
</body>
</html>
##### login.html #####
##### end #####
Explanation
1
This!is!a!link!to!the!protected!page!(page!3)!where!special!content!can!be!read!only!if!
the!visitor!has!typed!in!a!valid!username!and!password.
2
After!the!form!has!been!submitted,!the!PHP!script!(page!2),!auth.php,!will!be!
executed.!This!page!will!determine!whether!or!not!the!visitor!is!authorized!to!log!in.
3
The!visitor!is!asked!to!type!in!the!username!here.!See!Figures!16.36!and!16.37.
4
This!is!where!the!user!types!in!the!password.
5
To!submit!information!that!is!not!entered!by!the!visitor,!a!hidden!field!is!used!and!
assigned!the!value!"login".
!
Figure 16.36. Page 1: The login.html file.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 16.37. Page 1: The visitor fills out the form.
Example 16.26.
Code!View:!
(Page 2)
##### begin #####
##### auth.php #####
<?php
1 session_start();
// User is logging in
2 if (isset($_POST["login"])){
3 if (isset($_POST["username"]) && ($_POST["username"]
== "phpbee")
&& isset($_POST["password"]) && ($_POST["password"]
== "phpbee"){
4 $_SESSION["Authenticated"] = 1;
}
else{
5 $_SESSION["Authenticated"] = 0;
}
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
6 session_write_close();
7 header("Location: protected.php");
}
// User is logging out
8 if (isset($_GET["logout"])){
9 session_destroy();
10 header("Location: login.html");
}
?>
##### auth.php #####
##### end ####
Explanation
1
The!session!for!this!page!starts!here!for!auth.php!(page!2).
2
If!the!user!has!filled!out!the!login!form!in!login.html!(page!1),!then!the!
$_POST["login"]!variable!will!be!set,!and!the!statements!in!the!if!block!will!
be!executed.
3
If!the!username!is!set!and!has!a!value!"phpbee",!and!the!password!is!set!and!
also!has!the!value!"phpbee",!the!statement!in!line!4!is!executed.
4
The!session!variable!is!set!to!1.!The!value!of!1!will!be!used!later!to!determine!
that!the!user!is!logged!in.
5
If!either!a!valid!username!or!password!were!not!entered,!the!session!variable!
is!set!to!0.!A!value!of!0!will!be!used!to!determine!that!the!user!is!not!logged!
in.
6
The!session_write_close()!function!stores!the!session!data!now!and!closes!
the!session.
7
The!user!is!directed!to!protected.php!(page!3).!This!is!the!page!that!is!not!
accessible!to!anyone!who!is!not!logged!in.
8
If!the!user!entered!the!protected!page!and!clicked!the!link!to!log!out,!the!
variable!$_GET["logout"]!will!be!set,!and!the!statements!in!the!if!block!will!
be!executed.
9
The!session!and!all!its!data!are!destroyed.
10
The!user!is!redirected!back!to!the!login!page.!Because!the!session!was!
destroyed,!he!or!she!is!no!longer!authenticated!to!go!to!the!protected!page.
Example 16.27.
Code!View:!
(Page 3)
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
##### begin #####
##### protected.php #####
<?php
1 session_start();
?>
<html><head><title>Protected page</title></head>
<body>
<?php
2 if (isset($_SESSION["Authenticated"])
&& ($_SESSION["Authenticated"] == 1)){
?>
3 <h2>Protected content</h2>
<p>Hello. Since you are logged in, you can view protected
content</p>
4 <p>You can also <a href="auth.php?logout">log out</a></p>
<?php
}
else{
?>
<h2>You are not logged in</h2>
<p>Hello. Since you are not logged in, you cannot view
protected content</p>
5 <p>But you can <a href="login.html">log in</a></p>
<?php
}
?>
</body>
</html>
##### protected.php #####
##### end #####
Explanation
1
The!session!starts!for!page!3.!See!Figure!16.38.
2
If,!on!page!2,!the!session!variables!were!set!and!$SESSION["Authenticated"]!was!set!to!
1,!the!visitor!is!logged!in!and!will!be!able! t o!read!whatever!is!on!line!3.
3
This!is!where!the!content!would!be!added!for!this!page,!the!content!only!viewable!if!the!
user!successfully!logged!in.
4
This!link!will!send!the!user!back!to!page!2,!auth.php.!The!word!logout!appended!to!the!
question!mark,!will!be!passed!via!the!GET!method!and!assigned!to!the!$_GET[]!array.
5
This!link!returns!the!visitor!back!to!the!login!page,!page!1.
!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 16.38. Page 3: The visitor is logged in.
16.5. Chapter Summary
In this chapter we discussed how PHP uses cookies and sessions to maintain state; that is, save information between
different accesses to a Web page, allowing you to customize your applications based on user preferences, manage
logging in and out of your site, use links and hidden fields to pass session information back and forth, and so on.
What are the pros and cons of cookies versus sessions and vice versa? The cookie stores the visitor information on the
user’s computer even if a session has ended. The the lifetime of a cookie can be a long period of time or it can end when
the user closes his or her browser. A user can go to a Web site, browse around and come back, even log out and the
cookie can persist on his or her hard drive, keeping track of the user’s preferences, shopping cart information, number
of times he or she visited the site, and so on. But if the cookie has important information such as a password or user ID,
it is easy to read that information unless it is encrypted, and some people feel that cookies are a security threat because
they are passed back and forth across the network and are stored in a text-based readable files. Because a user can
disable cookies for his or her particular browser, you have no guarantee that they are being accepted.
PHP sessions are safer because they do not send any sensitive data over the network. They store the user information in
variables on the server. As you have seen in this chapter, even sessions rely on cookies because the session ID is
encrypted and normally passed in a cookie, but there are alternative ways to handle users who have disabled cookies for
their browser, such as passing the data in hidden form fields or URLs. Although this is considered insecure, you can
regenerate the session ID after using it or destroy all the session variables. The lifespan of sessions is normally the
length of a session, and after 24 minutes, the session files are deleted, but this can also be controlled in the php.ini
file. What if you have a cluster of servers? How will the session files be managed? At least with a cookie, only one
browser is necessary, no matter how many servers are involved. Which is best?
It has been said that over 90 percent of sessions use cookies, so perhaps a symbiotic relationship between the two is a
reasonable approach. Ultimately, you must weigh the pros and cons and decide what works best for you. (See
http://www.thescripts.com/forum/thread433783.html for further discussion.)
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
16.5.1. What You Should Know
Now that you have finished this chapter you should be able to answer the following questions:
1.
What!is!meant!by!stateless?
2.
What!are!cookies!used!for!and!where!do!they!reside?
3.
What!is!the!life!span!of!a!cookie?
4.
How!are!cookies!sent!from!the!server!to!the!browser?
5.
How!does!PHP!store!cookies?
6.
What!is!serialization?
7.
What!is!the!advantage!of!using!PHP!sessions?
8.
What!is!meant!by!a!cookieNbased!session?
9.
What!is!a!session!ID!number!and!where!is!it!stored?
10.
What!are!the!PHP!buffering!functions?
11.
How!are!sessions!registered?
12.
How!are!sessions!deleted?
13.
What!is!the!purpose!of!the!PHP!session_write_close()!function?
14.
What!is!garbage!collection?
15.
What!are!the!disadvantages!of!using!cookies?!What!are!the!disadvantages!of!
using!sessions?
16.5.2. What’s Next?
The next and last chapter introduces object-oriented programming with PHP. You will learn how to create classes to
encapsulate data and functions. You will create instances of a class, called objects, and assign properties to describe the
object. You will design methods, special functions, to manipulate the object and learn how to keep the object’s data
protected from outside access. You will see how one class inherits from another.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 16 Lab
1.
Create!a!login!page!that!asks!the!user!for!a!username!and!password.!Trim!the!
username!and!password!to!remove!any!unwanted!whitespace.!The!action!
attribute!of!the!from!will!redirect!you!to!a!new!page,!called!verify.php.
2.
The!verify.php!page!will!start!a!session!and!check!that!the!username!and!
password!fields!are!not!empty!and!also!that!they!are!correct.!If!not,!the!user!will!be!
informed,!and!redirected!back!to!the!login!page.!If!correct,!the!user!will!be!directed!
to!your!home!page!(you!may!want!to!use!the!database!form!from!the!last!exercise).
3.
When!the!user!is!ready!to!log!out,!end!the!session.
4.
Create!a!dropNdown!menu!that!allows!the!user!to!select!from!a!list!of!vacation!
spots.!Save!his!choices!in!a!cookie.
5.
Link!to!another!page!that!will!print!images!of!the!vacation!spots!that!the!user!
selected.
6.
When!the!user!returns!to!the!menu,!he!or!she!will!see!the!list!selected!the!last!time!
he!or!she!was!on!this!page.
!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 17. Objects
17.1. What Are Objects?
Objects are things we deal with every day. PHP deals with objects, as do most programming languages, and these
languages are called object-oriented programming (OOP). OOP is a way of trying to solve a problem in terms of real-
world objects. Some people are apprehensive at the thought of tackling this kind of programming, and are perfectly happy
to stick with top-down, procedural programs. Just as the everyday objects we use are not switchblades and hacksaws,
neither are programming objects. They are just a way of representing data.
As PHP has evolved from a tool for building simple home pages to a language for serious Web development, so has its
support for OOP. Once programs start to get larger and more complex, planning and design become more important.
Think of a simple home page put together with some family photos, links, and blogs. Then think of a Web site like
Amazon or eBay where there are thousands of forms, links, and transactions taking place all the time, all over the world—
the thought of putting something like that together is staggering. OOP is best suited to manage the complexity of such
large Web sites. Even if you do not program using objects, if you are reading and using PHP programs written by other
programmers, you are bound to run into this style of programming. This chapter gently introduces you to PHP objects and
some of the features that have been added to the language in PHP 5.
When talking about PHP data types in Chapter 4, “The Building Blocks,” we discussed two types: primitive types and
composite types. Like arrays, objects are composite types. They provide a way to organize a collection of data into a single
unit. Object-oriented languages, such as C++ and Java, bundle up data into a variable and call it an object. So does PHP.
Each object-oriented language you encounter is based on the same principles, but often the terminology is not exactly the
same when describing the concepts. You could say that PHP is like Java and C++, but has its own way of dealing with
objects.
When you learn about objects, they are usually compared to real-world things, like a black cat, a modern painting, or a
green pillow. Using the English language to describe an object, the object itself would be like a noun: a person, place, or
thing.
Nouns are described with adjectives. For the cat it might be described as fat and furry with green eyes, four legs, and a tail;
the painting is a British frigate, oil on canvas, and sells for $52,000; and the pillow is green silk, square, with dimensions
of 18″ × 18″. The adjectives that collectively describe these objects are called the properties (or attributes) of the object.
The object is made up of a collection of these properties.
In English, verbs are used to describe what the object can do or what can be done to it. The cat eats and sleeps, and its tail
twitches; the painting can be framed, sold, or purchased; the pillow’s dimensions can be increased or decreased, its fabric
and color changed, and so on. These verbs are functions called methods in object-oriented languages.
17.1.1. Objects and Classes
Objects are defined in a class. A class is a template or a blueprint that defines what an object should look like and what it
can do. A class represents a group of similar objects, such as a class of employees, a class of hotels, or a class of cars. The
object in a class is a concrete person, place, or thing. Like a cookie cutter, a class gives an object its form, and as with a
cookie cutter, you can build many objects of the same class. The employee object might be described to have a name,
address, and phone number. Although the object can later change its values, it still belongs to the same class. You can
change Bob’s phone number, but he is still in the employee class. You can change the color of the car, but it is still in the
car class.
A class contains a collection of variables (properties) and functions (methods). Like a blueprint, by itself the class does
nothing. It defines an object and its properties and methods. Properties describe the object. Methods are functions that
determine the behavior of the object; that is, what kind of actions can be performed on or by the object. As you can see in
Figure 17.1, a class is a unit consisting of a name for the class, in this case House, the variables that describe the house,
and the methods that describe the behaviors of the object, or what it can do. A class is an aggregate or composite data type.
Like an array that contains a collection of key–value pairs, the class represents a collection of properties and methods.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 17.1. A House class.
17.2. Working with Classes
17.2.1. Defining the Class
To#create#a#class#you#use#the#class#keyword#followed#by#the#name#of#the#class.#The#class#
definition,#like#a#function#definition,#is#enclosed#in#a#set#of#curly#braces.#The#name#of#a#class#
follows#the#same#naming#conventions#as#normal#variables#(minus#the#dollar#sign)#and#the#class#
name,#by#convention,#starts#with#a#capital#letter.#For#example:#
<?php
class House
{
<definition goes here>
}
?>
#
The#class#House#might#have#variables#(called#attributes)#such#as#$owner, $address,#$color,#or#
$number_of_rooms,#as#well#as#functions#(called#methods),#such#a#showHouse(),#cleanHouse(),#or#
paintHouse(),#for#example.#
Once#the#class#is#defined,#it#is#used#to#create#specific#objects.#Just#as#when#you#design#a#blueprint#
for#a#house,#the#real#house#does#not#yet#exist.#You#must#build#it#from#the#blueprint.#The#class#is#
analogous#to#the#blueprint#and#the#object#to#the#actual#house.#We#could#build#many#houses#from#
the#same#blueprint#and#we#can#build#many#objects#from#a#class.#Just#as#a#house#is#located#at#an#
address,#each#object#has#its#own#memory#address.#PHP#provides#the#address#and#cleans#up#the#
memory#when#the#object#is#no#longer#needed,#when#the#program#ends.#
Once#we#have#the#basic#stuff#of#which#houses#are#made,#we#can#extend#the#blueprint#to#add#new#
features#to#the#house,#such#as#a#new#family#room#or#a#fireplace.#Classes#can#also#be#extended#to#
create#more#refined#objects.#Extending#a#class#is#called#inheritance.#Inheritance#allows#the#
programmer#to#create#a#new#class#without#writing#a#brand#new#one.#He#or#she#can#reuse#an#
existing#class#and#add#some#new#features#and#functionality.#Inheritance#is#one#of#the#benefits#of#
OOP#that#we#discuss#later#in#this#chapter.#
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
17.2.2. Instantiating the Class
Once#the#class#is#declared,#the#object#needs#to#be#created.#In#the#real#world#you#would#build#a#
new#house;#in#the#objectKoriented#world,#you#would#instantiate#a#new#House#class#or#create#a#new#
instance#of#the#House#class.#To#make#a#new#object,#we#use#the#reserved#keyword#new.#To#
reference#the#object,#we#use#the#special#varia b le#called#$this.#Each#instance#of#a#class#has#the#
same#property,#but#different#copies,#so#that#the#values#can#be#different;#for#example,#if#you#have#
two#house#objects#of#the#same#class,#and#each#house#object#has#a#property#called#$owner,#the#
values#assigned#to#$owner#can#differ#from#house#object#to#house#object,#just#like#in#the#real#world.#
What’s “new”?
The#difference#between#an#object#and#a#class#is#that#a#class#is#conceptual#and#a n#ob ject #is#rea l.#
The#object#is#the#actual#variable#that#you#manipulate.#You#can#assign#and#retrieve#its#values,#pass#
it#to#functions,#delete#it,#copy#it,#and#so#forth.#It#holds#a#specific#set#of# data.#The#new#keyword#is#
used#to#create#a#PHP#object#that#is#an#“instance”#of#a#class.#
$myhouse = new House;
#
The#new#keyword#causes#PHP#to#look#for#a#class#named#House,#create#a#new#copy,#and#assign#it#to#
the#variable#$myhouse.#A#new#House#object#has#been#instantiated,#which#is#like#saying#“We#just#
built#a#new#house#and#called#it#$myhouse,”#and#to#make#another#object#from#the#House#blueprint,#
you#could#say:#
$yourhouse = new House;
#
Now#we#have#two#instances#of#the#House#class,#two#house#objects,#$myhouse#and#$yourhouse#(see#
Figure#17.2).#
Figure 17.2. Instantiating the House class.
#
#
#
The Properties and Methods
Properties#(variables)#and#methods#(functions)#together#are#called#class#“members.”#The#
properties#of#a#class#are#defined#as#variables.#Before#PHP#5,#the#keyword#var#was#used#to#define#a#
public#property#of#the#class;#that#is,#a#property#variable#that#is#visible#throughout#the#current#
PHP#script.#The#var#keyword#has#been#deprecated#as#of#PHP#5;#you#now#declare#public#
properties#with#the#public#keyword.#Methods#(class#functions)#default#to#public#so#you#do#not#
need#to#specify#them#as#public:#
(PHP#4)#
var $owner = "John Doe:;
var $address;
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
[...]... resources, and so on Typically, PHP releases the objects at the end of each script Being able to use a destructor is a PHP 5 feature PHP 4 does not have destructors at all In PHP 4 you created a function that simulated a destructor or you could use the PHP unset() function to force the removal of an object, but PHP 5 provides a specific destructor function named destruct() This method takes no parameters, and. .. Functions for Getting Class Information PHP provides a set of built-in functions that will return information about your class and its objects Table 17.1 provides a list of these functions For a complete list and examples of how these methods are used, see http://us3 .php. net/manual/en/ref.classobj .php 17.2.6 Encapsulation and Information Hiding Encapsulation and information hiding are closely related... name of the object precedes the arrow and the property or method so that PHP knows to which object the property and method apply Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Figure 17.3 A House class and creating a house object and accessing it The gettype() and get_class() Functions PHP provides a number of built-‐in functions... User-Defined Setters and Getters When you design a class, you are not required to use PHP s built-in methods; you can write your own customized getters and setters The properties can be declared as private and the only way they can be accessed is through the public setter and getter methods provided by the class, just another way to implement data hiding The disadvantage of having a setter and getter for... Inheritance and visibility with private, protected, and public variables 17.3 Some PHP 5 Object Features PHP 5 provided a number of new features for object-oriented programmers, some of which are discussed here and some of which are beyond the scope of this chapter Not included are some of the magic methods, cloning, abstraction, iterators, and interfaces 17.3.1 final Classes and Methods... Although functionally the same, PHP 4 and PHP 5 use a different syntax for creating constructor methods PHP 4 constructor methods are named with the same name as the class So, if you have a class named MyClass, the constructor is a function named MyClass PHP 5 provides the constructor, a magic method called construct() This method is not normally called directly by the user, but is automatically... assign values to properties in a class, PHP will automatically build or construct a new object when new is called by the user of the class When we created a new house, new employee, and new bank account, we did not explicitly call a constructor We let PHP create the object and assign the properties to it If you want to customize the initialization of an object, PHP lets you define a constructor method... compatibility with PHP 4, but both public and var are now acceptable 5 This is a function, called a method, defined for the class 6 A new object is created for the class Employee and assigned to a variable called $Heidi The $Heidi object is allocated its own copies of the properties defined within the Employee class 7–9 To assign values to the properties of the object, the object is followed by an arrow and the... Output from Examples 17.4 and 17.5 Example 17.5 < ?php # PHP 4 class House{ function House(){ // Constructor PHP 4 print "Constructor initializing a new house.\n"; } } /* End class definition */ 1 2 3 4 $my_house= new House; // Create object $your_house=new House; ?> Explanation 1 A House class is defined 2 When the function has the same name as the class, it is a constructor and will be invoked when... phrase, “Access private data with public functions.” Key principles of OOP are encapsulation and information hiding; that is, combining methods and properties into a class and keeping the class variables hidden from direct access by the class user Data hiding helps to protect the object’s data from being corrupted, and if the class implementation is modified, this should not affect the way the class is .
If!the!user!has!filled!out!the!login!form!in!login.html!(page!1),!then!the!
$_POST["login"]!variable!will!be!set, !and! the!statements!in!the!if!block!will!
be!executed.
3
If!the!username!is!set !and! has!a!value!"phpbee", !and! the!password!is!set !and!
also!has!the!value!"phpbee",!the!statement!in!line!4!is!executed manage
logging in and out of your site, use links and hidden fields to pass session information back and forth, and so on.
What are the pros and cons of cookies