PHP and MySQL by Example- P14

Chia sẻ: Thanh Cong | Ngày: | Loại File: PDF | Số trang:50

lượt xem

PHP and MySQL by Example- P14

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Tham khảo tài liệu 'php and mysql by example- p14', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả

Chủ đề:

Nội dung Text: PHP and MySQL by Example- P14

  1. } ?> Explanation 1 The  first  cookie  key–value  pair  is  set.  The  name  of  the  cookie  is  "usr"  and  the   corresponding  value  is  "Ellie Quigley". 2 The  second  cookie  key–value  pair  is  set.  The  name  of  the  cookie  is  "color"  and  the   corresponding  value  is  "blue".  Normally,  the  user  would  provide  the  value  from  a   form. 3 Because  cookies  will  not  become  visible  until  the  next  loading  of  the  page  where  the   cookie  should  be  visible,  you  can  test  if  a  cookie  was  successfully  set  before  extracting   its  contents.  See  Figure  16.3. 4 The  print_r  function  displays  the  contents  of  the  cookie.  If  the  cookie  had  not  been   set  or  had  expired  there  would  be  no  output  (see  Figure  16.2).  All  the  other  attributes   set  for  the  cookie,  like  expiration  date,  path,  security,  and  so  on,  are  not  visible.   Figure 16.2. The first time the page is viewed the $_COOKIE array is empty. Please purchase PDF Split-Merge on to remove this watermark.
  2. Figure 16.3. When the page is refreshed, the $_COOKIE array has cookie values.   Please purchase PDF Split-Merge on to remove this watermark.
  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.       Please purchase PDF Split-Merge on to remove this watermark.
  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. Example 16.2. Code  View:   Multiple Cookie Values The Cookie Array? $_COOKIE[]
  5. one  string,  we  only  need  to  call  setcookie()  once. 3 Check  to  see  if  the  cookie  has  any  value,  that  is,  if  it  was  set. 4 The  cookie  data  is  retrieved  for  the  user  and  assigned  to  $cookie_data.  It  is  a  serialized   string.  See  Figure  16.6. 5 The  slashes  are  stripped  from  the  string.  If  you  do  not  remove  the  backslashes,  the   unserialize()  function  on  the  next  line  fails. 6 The  unserialize()  function  returns  the  original  array. 7 You  can  see  in  the  value  of  the  cookie  the  serialized  array. 8 The  unserialized  array  is  printed.  We  now  have  the  original  values  back.  See  Figure  16.6.   Figure 16.6. Storing an array in a single cookie.     Please purchase PDF Split-Merge on to remove this watermark.
  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. Example 16.3. Setting Cookies Visitor Count with Cookies You are visitor number . Explanation 1 The  value  stored  in  the  $_COOKIE  array  is  extracted  and  assigned  to  $count.   The  value  is  just  an  integer  that  continues  to  be  incremented  by  1  each  time   the  user  reloads  the  page.  If  this  is  the  first  time  the  page  has  been  loaded,  the   $_COOKIE  array  will  be  empty. 2,   If  this  is  the  first  time  the  user  has  visited  this  page,  $count  will  be  empty,  and   3 it  will  be  set  to  1.  See  Figure  16.7. 4 For  each  subsequent  visit  to  this  page,  the  value  of  the  counter  will  be   increased  by  1.  See  Figure  16.8. 5 The  setcookie()  function  sets  the  cookie  when  the  page  is  first  loaded.  The   name  of  the  cookie  is  visits  and  the  value  stored  there  will  be  incremented   by  1  each  time  the  page  is  revisited.  The  cookie  is  stored  on  the  user’s   browser  and  will  be  deleted  when  the  browser  is  exited.  What  is  important  to   note  here  is  that  the  cookie  is  sent  in  a  header,  and  headers  must  be  sent   before  any  other  output  from  this  page.  The  HTML  output  is  placed  after  this   line  or  PHP  will  send  warnings  to  the  screen. Please purchase PDF Split-Merge on to remove this watermark.
  7. Figure 16.7. Cookies used to count visitors.   Figure 16.8. The cookie value is incremented each time the page is reloaded. Please purchase PDF Split-Merge on to remove this watermark.
  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. Code  View:   (Page 1--The HTML page) Setting Cookies Tracking Visitors with Cookies Welcome to our Site! 1 Check out our product line Click here ------------------------------------------------------------------ (Page 2--The PHP Script--Set a Cookie) Products Products Page Explanation 1 When  the  user  clicks  on  the  link  in  this  HTML  form,  he  or  she  will  be  directed  to  the   page  (page  2)  that  contains  the  code  for  setting  a  cookie.  The  initial  form  is  shown  in   Figure  16.9. 2 After  clicking  the  link  (Figure  16.9)  in  page  1,  the  user  is  directed  to  page  2,  the   “Products  Page”  (Figure  16.10).  The  variable  is  assigned  a  string  of  arguments  that  will   be  sent  to  the  PHP  date()  function  on  the  next  line,  the  current  date  and  time  on  the   server.  (Keep  in  mind  that  the  date  on  the  browser  and  server  might  not  be  in  sync.) Please purchase PDF Split-Merge on to remove this watermark.
  9. “Products  Page”  (Figure  16.10).  The  variable  is  assigned  a  string  of  arguments  that  will   be  sent  to  the  PHP  date()  function  on  the  next  line,  the  current  date  and  time  on  the   server.  (Keep  in  mind  that  the  date  on  the  browser  and  server  might  not  be  in  sync.) 3 The  cookie  is  set  with  the  setcookie()  function.  The  first  argument,  "message",  is  the   name  of  the  cookie  and  the  second  argument,  "$last_visit",  is  the  value  that  will  be   stored  in  the  cookie. 4 The  first  time  this  page  is  accessed  the  cookie  is  set.  Its  value  will  not  be  available  until   the  next  time  the  page  is  viewed.  If  the  cookie  has  a  value  (i.e.,  is  not  empty),  the   message  will  contain  the  date  string  that  was  assigned  to  the  cookie  by  the  setcookie()   function  in  the  previous  viewing  of  the  page. 5 The  value  of  the  cookie  is  extracted.  It  is  the  date  string  that  was  assigned  to  the  cookie   the  last  time  the  visitor  viewed  this  page.  Every  time  the  visitor  refreshes  this  page,  the   value  of  the  cookie  will  be  the  cookie  value  that  was  set  on  his  or  her  last  visit,  that  is,   the  date  and  time  of  the  last  visit.   Figure 16.9. The HTML initial form (page 1).     Please purchase PDF Split-Merge on to remove this watermark.
  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 to expire. Table 16.1. Units of Time in Seconds Unit  of  Time Seconds Minute 60 Hour 60 * 60 Day 60 * 60 * 24 Week 60 * 60 * 24 * 7 Month 60 * 60 * 24 * 30   Please purchase PDF Split-Merge on to remove this watermark.
  11. Format int time ( void )   Example: $nextWeek = time() + (60 * 60 * 24 * 7); (60 seconds * 60 minutes * 24 hours * 7 days) Example 16.5. Explanation 1 The  variable  is  assigned  the  value  of  one  month,  30  days,  from  now  in   milliseconds. 2 The  setcookie()  function  is  named  message,  it  contains  the  date  of  the  last   visit,  and  it  will  expire  in  one  month.  The  expire  value  is  calculated  by  adding   the  number  of  seconds  in  a  month  to  the  current  time  (time()).  After  one   month,  if  the  visitor  returns,  the  cookie  will  be  reset. 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. Example 16.6.
  12. The Cookie Array? < Code continues here > Explanation The header information must be sent first, or a warning is issued, as in Figure 16.11. Even a blank line will cause a warning. 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. Please purchase PDF Split-Merge on to remove this watermark.
  13. Table 16.2. Buffering Functions Function What  It  Does ob_start() Enables  output  buffering.  No  output  is  sent  from  the  script  (other  than   headers).  It  is  saved  in  an  internal  buffer. ob_end_flush() Flushes  the  output  buffer,  and  disables  output  buffering. ob_end_clean() Cleans  the  output  buffer  without  sending  it,  and  disables  output   buffering. ob_get_clean() Returns  the  contents  of  the  output  buffer  and  ends  output  buffering ob_get_length() Returns  the  length  of  the  output  buffer. ob_get_contents() Returns  the  current  output  buffer  as  a  string.  This  allows  you  to  process   whatever  output  the  script  emitted. ob_gzhandler() A  callback  function  for  ob_start().  Useful  for  sending  compressed  data.   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. Format bool ob_start ( [callback output_callback [, int chunk_size [, bool erase]]] ) bool ob_end_flush ( void )   Example: ob_start(); ob_end_flush(); Example 16.7. Code  View:     The Cookie Array? $_COOKIE[]
  14. ?> Explanation 1 The  ob_start()  function  turns  on  output  buffering.  Now  only  HTTP  headers   will  be  sent  and  the  rest  of  the  program’s  output  will  be  saved  until  the   program  ends,  at  which  time  it  will  be  sent. 2 The  setcookie()  function  can  be  placed  below  the  other  ouput  without   causing  warnings.  This  output  will  be  sent  first  due  to  the  buffering  set  up  on   line  1. 3 The  ob_end_flush()  function  is  not  necessary,  but  is  used  here  to  flush  out  the   buffers  and  end  the  output  buffering  for  this  session. 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:   Code  View:   ; 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”. Please purchase PDF Split-Merge on to remove this watermark.
  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. Example 16.8. Explanation 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. Please purchase PDF Split-Merge on to remove this watermark.
  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, book|s:7:"History";user|s:13:"Ellie Quigley"; Please purchase PDF Split-Merge on to remove this watermark.
  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. Format string session_save_path ( [string path] )   Example: session_save_path("/newpath"); echo session_save_path();   Example 16.9.
  18. 2 if ($handle = opendir(session_save_path())) { echo "Files:< br />\n"; /* Loop over the directory. */ 3 while (false !== ($file = readdir($handle))) { echo "$file< br />\n"; } echo ""; closedir($handle); } ?> Explanation 1   The  session_save_path()  function  returns  the  path  location  where  the  session  files  are   stored.   2   The  opendir()  function  opens  the  directory  folder  where  the  session  data  is  stored  and   returns  a  handle  to  that  directory,  $handle.   3   The  readdir()  function  retrieves  the  contents  of  the  directory,  and  its  output  is  displayed   in  Figure  16.15.     Figure 16.15. The session path and files. Output from Example 16.9.     Please purchase PDF Split-Merge on to remove this watermark.
  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();   Please purchase PDF Split-Merge on to remove this watermark.
  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. Format   Example: $_SESSION['username'] = "john"; $_SESSION['password'] = $_POST['passwd'];   Example 16.10. Sessions Tracking Visitors with Sessions Explanation 1   The  session  is  started  here.  All  scripts  using  sessions  start  with  the  session_start()   function.   2   If  the  session  variable  has  not  been  set,  this  is  the  start  of  a  brand  new  session.  A  session   ID  will  be  assigned  and  the  $_SESSION  array  will  be  initialized  on  the  next  line.   Please purchase PDF Split-Merge on to remove this watermark.
Đồng bộ tài khoản