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

Tài liệu PHP and MySQL by Example- P14 pptx

50 433 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 đề PHP and MySQL by Example
Trường học University of Information Technology
Chuyên ngành Computer Science
Thể loại Lecture Notes
Năm xuất bản 2024
Thành phố Ho Chi Minh City
Định dạng
Số trang 50
Dung lượng 1,88 MB

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

Nội dung

The session file contains the actual session data; for example, username, preferences, or items in the shopping cart—information about the visitor that was stored the last time he or she

Trang 2

Figure 16.3 When the page is refreshed, the $_COOKIE array has cookie values

Trang 3

Figure 16.4 The browser sends the cookie back to the server; the server sets the cookie in a header See Figure

16.5, a diagram illustrating server/browser/PHP interaction with cookies

Figure 16.5 The cookie is sent in an HTTP header

Trang 4

Storing Multiple Values in One Cookie—Serialization

The setcookie() function accepts one string as its value In the previous example, the setcookie() function was called twice to register two cookie values Because the number of cookies is limited to 20 per domain, you might want to assign multiple values to one cookie, for example, data coming in from a form In the following example, one cookie will store three values This example demonstrates how to serialize data Serializing the data allows you to convert an array into a string that will be accepted by the cookie After retrieving the cookie contents, you will have to unserialize it to convert the string back to an array

The PHP serialize() function returns a string containing a byte-stream representation of the value, making the value acceptable for storage anywhere—in this example, a cookie, though serialization is also used for storing variables and objects in a file or database (If you go to your browser and look at the actual data stored in the cookie, it has been URL-encoded.)

Use unserialize() to return the string to its orginal form

<html><head><title>Multiple Cookie Values</title></head>

<html><head><title>The Cookie Array?</title></head>

Trang 5

$cookie_data

unserialize()unserialize()

Figure 16.6 Storing an array in a single cookie

Trang 6

16.3.2 Tracking Visitors with Cookies

The following examples demonstrate the use of cookies for tracking vistitor activities, such as when the visitor last viewed the page and how many times he or she has been there, but they can also be used to check user preferences, user IDs, and so on Cookies are useful for retaining small amounts of information, but not all browsers support cookies and

if they are supported, a user can turn them off To overcome these problems, a better solution is to use PHP sessions (discussed in “What Is a Session?” on page 694 of this chapter)

Visitor Count Example

The following example uses a cookie to count the number of times the user has visited this page Once the cookie is set, its value will be increased by 1 each time the visitor comes back to the page

<font size=+1 face="arial">

<h2>Visitor Count with Cookies</h2>

You are visitor number <?php echo $count; ?>.<br />

Trang 7

Figure 16.7 Cookies used to count visitors

Figure 16.8 The cookie value is incremented each time the page is reloaded

Trang 8

Tracking the Visitor’s Last Visit

The following example keeps track of when a visitor last viewed the page The cookie will store the current date, which will be retrieved the next time the page is refreshed

Example 16.4

(Page 1 The HTML page)

<html><head><title>Setting Cookies</title></head>

<body bgcolor="lavender">

<font size=+1 face="arial">

<h2>Tracking Visitors with Cookies</h2>

<H1>Welcome to our Site!</H1>

<p>

1 Check out our product line

<a href="http://localhost/exemples/sessions/message.php"> Click here</a>

</font>

</body>

</html>

- (Page 2 The PHP Script Set a Cookie)

<?php

// Filename: "message.php"

2 $date_str="l dS \of F Y h:i:s A";

$last_visit="Your last visit was on " date("$date_str");

Trang 10

Figure 16.10 After returning to this page, the cookie value is displayed

16.3.3 Extending the Life of a Cookie

How long will a cookie stay in the cookie jar? Normally a cookie expires when the browser is exited However, the cookie’s life span can be controlled by setting the expiration date in the cookie’s expire attribute, the third argument

in PHP’s setcookie() function The time the cookie expires is represented as a UNIX timestamp; that is, the number of seconds since January 1, 1970, 00:00:00 GMT, known as the epoch The time() function will give you the current time in seconds, and by adding additional seconds, you can set the expiration date of a cookie to some time in the future By subtracting from this value, the time will be past time, which will cause the cookie to be deleted The time returned is expressed in GMT time, the required format for the expire attribute

To get the time, two PHP functions are provided: time() and mktime()

The time() Function

The time() function returns the current time in UNIX time (UNIX timestamp) By adding the number of seconds to the output of the time() function, you can set the amount of time from now until some future time when the cookie is

Trang 11

$date_str="l dS \of F Y h:i:s A";

$last_visit="Your last visit was on " date("$date_str");

1 $expire=60*60*24*30 + time(); // One month

The mktime() Function

The mktime() function will also get the UNIX time It has a different format Arguments can be set to 0 (zero) from left to right if you want to use the default values However, you can leave out arguments on the right side to get the defaults (The year is either two or four digits.)

Format

int mktime ( [int hour [, int minute [, int second [, int month [, int day [, int year [, int is_dst]]]]]]] )

Example:

$lastday = mktime(0, 0, 0, 6, 0, 2006); // Last day of May echo

date("M-d-Y", mktime(0, 0, 0, 1, 1, 2006)); // "Jan-01-2006"

16.3.4 Buffering and HTTP Headers

Because cookies are sent in an HTTP header, you cannot execute any other output before sending the header or you will get a PHP warning In the following example, the fact that there is a blank line at the top of the file caused the warning The cookie headers must be set first unless you turn on buffering

Trang 12

<head><title>The Cookie Array?</title></head>

Figure 16.11 Header information should be sent first!

If you need to precede any HTTP headers (not just cookie headers) with other output, PHP provides a set of buffering functions that allow you to save all the script’s output in a buffer until the script ends (starting with PHP 4.0) When the script ends, first the HTTP headers, and then the contents of the output buffer, are sent to the browser

The functions that help you control output buffering are shown in Table 16.2

Trang 13

Table 16.2 Buffering Functions

The ob_start() and ob_end_flush() Functions

The ob_start() function enables output buffering and the ob_end_flush() function flushes out the buffers and then turns buffering off When your script ends, PHP will automatically flush the buffers, so you can omit

ob_end_flush() It is possible to call ob_start() multiple times; and if so, you would have to call

ob_end_flush() for each level

Trang 14

Output Buffering and php.ini

If you want buffering set for all your PHP scripts, you can enable the php.ini directive output_buffering If you do, every PHP script will behave as if it begins with a call to ob_start()

From the php.ini file:

; Output buffering allows you to send header lines (including cookies) even

; after you send body content, at the price of slowing PHP's output layer a

; bit You can enable output buffering during runtime by calling the output

; buffering functions You can also enable output buffering for all files by

; setting this directive to On If you wish to limit the size of the buffer

; to a certain size -you can use a maximum number of bytes instead of 'On', as

; a value for this directive (e.g., output_buffering=4096)

output_buffering = Off

Output buffering is turned off by default If you want to turn it on for all scripts, go to the php.ini initialization file and change the output_buffering directive to “On”

Trang 15

16.3.5 Deleting a Cookie

When cookies are created, they are, by default, deleted when the user closes his or her browser You have seen how to expand the life of a cookie, but what if you want to delete the cookie right now, even before the user closes his or her browser? Instead of adding to the current time, you simply subtract from the current time to some earlier date This will cause the cookie to be deleted right away

Remember, deleting a cookie is the responsibility of the browser and the time settings there might be different from the time settings on the server Even though technically setting the expiration time to –1 would be an earlier time, it might

be better to set it to a bigger negative number to assure that it will be removed Setting the expiration time to 0 has no effect

Because we are destroying the cookie, there is no point in giving it a value, thus the second argument is

intentionally left empty

Using the Browser to Remove Cookies

Another way to delete cookies is to go in your browser to the Tools menu in Navigator, then to the Cookie Manger, and then to Manage Stored Cookies In Internet Explorer, go to the Tools menu and Internet Options Then you can remove all or some cookies from the hard drive Figure 16.12 shows you how the Firefox browser manages cookies by going to Tools, Options, Privacy

Figure 16.12 Cookie management on the Firefox browser

16.4 What Is a Session?

Simply put, a session is the time that a user spends at a Web site PHP provides us with a mechanism to manage sessions so that we can keep track of what a visitor is doing, what he or she likes, what he or she wants, and so on, even after the user logs off Like cookies, the idea is to maintain state Before delving into the details, let’s use an analogy to give you an idea of how sessions work

Trang 16

Imagine taking your favorite wool sweater to a dry cleaning establishment You will drop off the sweater and be handed

a claim ticket that will be used to identify the sweater when you return The other half of the claim ticket is pinned to your sweater with the same number you have on your claim ticket Later when you come back, you will give your claim ticket to the attendant and he or she will use it to identify your sweater in the long rack of clothes A session works the same way

A PHP session, like a cookie, is a way for the PHP to keep track of that Web site visitor even after he or she leaves or logs off A visitor makes a request from his or her browser to retrieve a Web page as follows:

http://server/homepage.php

The server program, in this example, homepage.php, is a PHP program PHP starts a session and sends a unique session ID number, similar to the claim ticket, back to the visitor’s browser This unique ID number is a long random hexadecimal number that is used to key into the user’s data It can be sent via a cookie or added to all URLs of the pages for the site The actual user information is saved in a session file on the server, usually in a temporary directory (see Figure 16.13) The session filename contains the unique ID number for the session The next time the visitor asks for the page, his or her browser hands the ID number back to the server, just as you hand the claim ticket to the dry cleaning attendant The server uses the session ID number to locate the file with the name that corresponds to the same session ID number The session file contains the actual session data; for example, username, preferences, or items in the shopping cart—information about the visitor that was stored the last time he or she visited the page If this is the first time the user has visited the page, his or her preferences will be collected and stored into the session file, to be retrieved later on

Figure 16.13 The session data is stored in a /tmp directory on the server

By default, the session ID is sent in a cookie and the cookie’s name is PHPSESSID Unlike the cookies we discussed in the first part of this chapter, where the user information was passed in a cookie, with sessions, the only data in the cookie is the session ID, not any other information about the user The user information is saved in a session file on the server so that the size limitation of cookies is not a factor and sensitive information is not being passed back and forth across the network

This session file starts with “sess” followed by the session number (Apache/Windows) The text it contains is a

serialized line representing the data, the data type, and the number of characters saved for a session.[2] This is a line from a session file:

[2] Because the (session) library uses different storage modules, you can keep the data in plain-text files, shared memory, or databases The exact location of data is not really important (as long the performance of the medium is sufficient) From Tobias Ratschiller, http://www.zend.com/zend/tut/session.php

book|s:7:"History";user|s:13:"Ellie Quigley";

Trang 17

Once the user’s browser has a session ID, it passes that ID back to the server program on every subsequent request The session ID is disposable, so after some time it will expire and the information associated with it will also be removed A session might last for a few minutes or a few hours since the last request or it could last indefinitely We look at various configuration options later in this chapter Figure 16.14 illustrates the way the session ID is passed in a cookie

Figure 16.14 The cookie file and the session file have the session ID in common

Although cookies are the default way to pass the session ID back and forth between browser and server, you can also pass the session ID as GET or POST data in the same way as when submitting a form Recall that GET data is URL-encoded and attached with a ? to the URL, whereas the POST data is part of the page header information It is also possible to send a session ID through a URL with a link within a page

16.4.1 Where to Store Sessions

If your site is sharing a server, it is recommended that session files for users should be in their own user area under the server, but not in a world writable directory such as /tmp If a site has a large number of users and session files, it is possible to store the session files in multiple levels of subdirectories To find out where your sessions are stored, or to change the default path, see session.save_path in the php.ini file or use PHP’s session_save_path() function

From the php.ini file:

; session.save_path = "N;/path" ; ; where N is an integer Instead of storing all the session files in ; /path, what this will do is use subdirectories N-levels deep, and ; store the session data in those directories This is useful

if you ; or your OS have problems with lots of files in one directory, and is ;

a more efficient layout for servers that handle lots of sessions ;

The session_save_path() function returns the path of the current directory used to save session data If a path is specified, the path to where data is saved will be changed for this session If this page will be linked to other pages, then the function must be called before starting the session in all the pages involved Of course, PHP will need read and write access to the new path to retrieve and save session data

Trang 18

2 if ($handle = opendir(session_save_path())) {

echo "<b>Files:< br />\n";

/* Loop over the directory */

3 while (false !== ($file = readdir($handle))) { echo "$file< br />\n";

Trang 19

16.4.2 Starting a Cookie-Based Session

A PHP session is started either explicitly with the session_start() function, or implicitly by registering a variable for the session with the session_register() function Typically, session_start() is called on top of the page, and then session variables are registered in the superglobal $_SESSION array

When PHP starts a session, it has to check first to see whether a valid session ID already exists for this user If a valid session ID does exist, PHP will go to the session file that corresponds to the ID number, retrieve the data from the file, and assign it to the superglobal $_SESSION associative array The values in this array are then made available to your program If this is the first time the user has visited the page, PHP will create a new session ID, and the $_SESSION array will be empty

The session_start() Function

The session_start() function creates a session or resumes one that has already started The session ID is passed via a cookie, via GET/POST, or in a link (see a cookie-based session in Figure 16.16) Each page that uses a session must start the session with the session_start() function If the session ID is being sent by a cookie, then as with all cookie headers, the session_start() function is called before any other statements that send output to the browser This function always returns TRUE

Figure 16.16 A cookie-based session Note the session ID is sent as an HTTP Cookie header

Format

bool session_start ( void )

Example:

session_start();

Trang 20

16.4.3 Registering a Session

The data that is stored in the session file is created in a PHP script in the form of variables The session variables can then be referenced across page requests during the life of a session These variables might represent the items placed in

a shopping cart, a user’s login and password, a user’s color preference, and so on

Although session_start() starts a session, it does not register session variables To create session variables, you must register the variables in the session library This can be done in two ways We address both methods next

The $_SESSION Associative Array

To register variables for the session, the preferred way is to assign values to the superglobal $_SESSION array Superglobals are available everywhere in your script, even within functions PHP automatically registers the

$_SESSION variables for you The global $_SESSION associative array is used to handle the session variables that will be saved on the server for the life of the session The key for the $_SESSION associative array is the name of the variable, and the value is what you are assigning to it

To access the values in the $_SESSION associative array, you must first start a session and then extract the array values as you would any other associative array

To unset these variables, the unset() function is used; for example, unset($_SESSION['color'])

You must use session_start() before using the $_SESSION array

<font size=+1 face="arial">

<h2>Tracking Visitors with Sessions</h2>

<?php

2 if ( ! isset($_SESSION)){

3 $_SESSION[visitor_count]=0;

} else{

Trang 21

Figure 16.17 Using the $_SESSION array to save and retrieve a session Initial output from Example 16.10

Figure 16.18 Each time the user refreshes this page, the count is incremented by 1

Trang 22

The session_register() Function

The traditional way to register session variables was to use the PHP session_register() function, but to use this function you must set register_globals to “On” in the php.ini file, no longer the default setting If, on the other hand, you are using the session_register() function, once registered in the session library, these global variables will be available until the session ends or until the session_unregister() function is called Unlike registering session variables with the $_SESSION array, with the session_register() function it is not

necessary to call session_start() first After registering a variable, PHP will make an implicit call to

session_start()

The arguments to session_register() can be strings containing the name of a variable or an array name Note that this function takes the name of a variable as argument, not the variable itself

The session_is_registered() function can be used to check if a session variable has been set and

session_unregister() to remove variables from the session; for example, to remove a product item from the shopping cart These functions should not be used if you are registering sessions with the $_SESSION array

Format

bool session_register ( mixed name [, mixed ] )

Example:

session_start(); session_register('username'); session_register('password');

16.4.4 Saving Arrays in a Session

When using a shopping cart, you can add multiple items to your cart, browse around, come back, delete some items, and go on like this until you submit your order A program that collects this data can store it in an array and save the data with a session The $_SESSION array accepts simple scalar variables, but can also accept arrays The following example demonstrates how to register multiple items in a session, list the saved values on another page, return to the selection page, and add more items to the array

Example 16.11

(Page 1)

<?php

Trang 25

<table width="25%" border='1'>

<caption><b>Selected Book Categories</b></caption>

<col span="1" width="100"/>

$_SESSION['choices']

Ngày đăng: 21/01/2014, 09:20

TỪ KHÓA LIÊN QUAN