Page 334 - Beginning PHP 5.3
P. 334
Part III: Using PHP in Practice
Summary
PHP scripts start to become much more useful when they can store data on a semi - permanent basis. In
this chapter, you learned how to use three different techniques — query strings, cookies, and sessions —
to store data related to a particular user between page requests:
❑ Query strings are simple to understand and use, but they are not at all secure so they ’ re best
used for transmitting innocuous information. You learned how to build query strings with
urlencode() and http_build_query() , as well as how to read data from query strings, and
you created a simple example that uses query strings to create a paged display .
❑ Cookies are a step up from query strings, because you don ’ t have to pass data between every
single page request. Cookies can even persist when the browser is closed and reopened. You
looked at the anatomy of a cookie, and learned how to create cookies, read cookies via the $_
COOKIE superglobal, and delete cookies. You also wrote a script that uses cookies to remember
details about a visitor .
❑ Sessions have a couple of major advantages over cookies: they ’ re more secure, and they don ’ t
involve sending potentially large amounts of data to the server each time a page is viewed. You
explored PHP ’ s built - in session - handling functionality, including session_start() , the $_
SESSION superglobal, session_write_close() , and session_destroy() . You learned that,
though not advisable, you can pass session IDs in query strings in situations where the browser
doesn ’ t support cookies, and you looked at some ways to fine - tune PHP ’ s session behavior.
Finally, you used sessions to create a simple shopping cart and user login/logout system .
Now that you know how to save state, you can start to write more powerful, persistent Web applications
that can remember session information between page views.
In the next chapter you look at how to access the Web server ’ s file system from within your PHP scripts.
This means that you can store application data and other information in files on the server ’ s hard drive,
further expanding the capabilities of your Web applications.
Before you leave this chapter, take a look at the following two exercises, which test your knowledge of
cookie and session handling in PHP. You can find the solutions to these exercises in Appendix A.
Exercises
1. Write a script that uses cookies to remember how long ago a visitor first visited the page.
Display this value in the page, in minutes and seconds.
2. In Chapter 9 you created a three - step registration form using hidden form fields. Rewrite this
script to use sessions to store the entered form data, so users can come back to the form at
another time and continue where they left off. Remember to erase the entered data from the
session once the registration process has been completed.
296
9/21/09 9:05:18 AM
c10.indd 296
c10.indd 296 9/21/09 9:05:18 AM