C h a p t e r 9 : M y S Q L , S e s s i o n s , a n d C o o k i e s 221 C h a p t e r 9 : M y S Q L , S e s s i o n s , a n d C o o k i e s 221 echo "Using MySQL Sanitize String<xmp>"; echo "Before: " . $string . "\n"; echo "After: " . PIPHP_MySQLSanitizeString($string); echo "</xmp>"; The <xmp> tag sets the typeface to a form that indicates example text. The PIPHP_ SanitizeString() function is quite straightforward, but there are two important things to note about the PIPHP_MySQLSanitizeString() function. These are that the function will generate an error if it is called when a connection to a database is not already open (which is why the preceding example creates a database connection before calling it): and you must make sure that PIPHP_SanitizeString() is also pasted into your program, or otherwise included by it, because it is referenced. The Plug-ins function PIPHP_SanitizeString($string) { $string = strip_tags($string); return htmlentities($string); } function PIPHP_MySQLSanitizeString($string) { if (get_magic_quotes_gpc()) $string = stripslashes($string); $string = PIPHP_SanitizeString($string); return mysql_real_escape_string($string); } Create Session If you have a web site that a user can join, then you need a way to keep track of that person as they navigate through the site. Not for reasons of spying on them or anything like that, but purely in order to keep them logged in and to offer them all the benefits that membership provides. Figure 9-5 shows this plug-in being used to create a session and read back one of the session variables. FIGURE 9-5 Creating a PHP session allows you to maintain a user’s details across multiple pages. 65 222 P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s 222 P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s About the Plug-in This plug-in takes all the same details about a user we have previously been storing in a MySQL database and saves them in PHP session variables. It requires these arguments: • $handle A username • $pass A matching password • $name The user’s real name • $email The user’s e-mail address Variables, Arrays, and Functions $_SESSION['handle'] The user’s handle stored in a session variable $_SESSION['pass'] The user’s password stored in a session variable $_SESSION['name'] The user’s name stored in a session variable $_SESSION['email'] The user’s e-mail address stored in a session variable $_SESSION['ipnum'] The user’s IP number stored in a session variable $_SESSION['agent'] The user’s web browser User Agent string stored in a session variable How It Works This is a plug-in that provides convenience more than anything else because it simply starts a new PHP session using the session_start() function and then assigns the values passed to the plug-in to the various session variables. If the session can’t be started, then FALSE is returned; otherwise, TRUE. One reason the call may fail is if any text has already been output by your program. This is because session details are often stored in cookies (unless the user has cookies disabled, in which case they are stored in the query string), and therefore they must be exchanged between the server and browser before any other data. You should note how the user’s IP address and the User Agent string supplied by their browser are also saved as session variables. You will see how they will be used later in plug- in 68, Secure Session. Don’t worry about this method possibly storing private details, such as a username and password, anywhere unsafe because it doesn’t. PHP stores these details internally and they are never sent to the browser. Instead, an identifying token is all that is ever passed back and forth between the server and browser. How to Use It In order to use this plug-in, you already need to have available the four items of data about a user to store in the session variables. These may have been input by the user or retrieved from a MySQL database, but in the following example they are simply assigned to some variables and then the PIPHP_CreateSession() function is called: $handle = "firstprez"; $pass = "GW022232"; $name = "George Washington"; $email = "george@washington.com"; $result = PIPHP_CreateSession($handle, $pass, $name, $email); C h a p t e r 9 : M y S Q L , S e s s i o n s , a n d C o o k i e s 223 C h a p t e r 9 : M y S Q L , S e s s i o n s , a n d C o o k i e s 223 Upon success, $result will have the value TRUE; otherwise, it will be FALSE. You can act on this value in the following manner, which displays the contents of one of the session variables to demonstrate that the call succeeded: if (!$result) echo "Could not create session."; else { echo 'Session created.<br /><pre>'; echo 'Testing: $_SESSION[\'handle\'] = ' . $_SESSION['handle']; } For correct results make sure that you only call this plug-in before you output any text, otherwise session creation and variable assignment may fail. The Plug-in function PIPHP_CreateSession($handle, $pass, $name, $email) { if (!session_start()) return FALSE; $_SESSION['handle'] = $handle; $_SESSION['pass'] = $pass; $_SESSION['name'] = $name; $_SESSION['email'] = $email; $_SESSION['ipnum'] = getenv("REMOTE_ADDR"); $_SESSION['agent'] = getenv("HTTP_USER_AGENT"); return TRUE; } Open Session Once you have used PIPHP_CreateSession() to store a user’s details, any other pages (or even the same one if called up separately) can easily retrieve these values using this plug-in. Figure 9-6 shows data that has been saved in a session using the PHP program file plugin65. php, being fully recalled by calling up plugin66.php. FIGURE 9-6 With this plug-in, a single function call will retrieve a range of user details, even across different web pages. 66 224 P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s 224 P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s About the Plug-in This plug-in opens a previously created PHP session and returns the session variables stored in it. It does not require any arguments. Variables, Arrays, and Functions $vars Array containing the various session variables’ values How It Works This plug-in first attempts to start a session using the session_start() function. If that fails for any reason, a single-element array with the value FALSE is returned. One reason it could fail is if a session is already open, which is why the @ symbol prefaces the function call; it is there to suppress any error messages. If a session is successfully opened, a check is then made for one of the session variables that ought to be set, namely $_SESSION['handle']. If it’s not set, an error has occurred and a single-element array with the value FALSE is returned. Otherwise, everything seems to be in order so the array $vars is initialized and then the four main user session variables are inserted in to this array and a two-element array is returned, the first of which has the value TRUE, while the second contains the $vars array. How to Use It Using this plug-in is as easy as making a short function call, like this: $result = PIPHP_OpenSession(); If $result[0] has the value FALSE, an error occurred; otherwise, $result[1] contains a sub-array that will itself contain the four main items of user details. Y ou can use code such as the following to act on the value of $result[0] and retrieve the details: if (!$result[0]) echo "Could not open session."; else list($handle, $pass, $name, $email) = $result[1]; Here, use has been made of the list() function, which takes an array and assigns its elements to the variables passed to it, providing an excellent means of quickly retrieving the four values. It could be considered shorthand code for the following: $handle = $result[1][0]; $pass = $result[1][1]; $name = $result[1][2]; $email = $result[1][3]; Whichever method you use, you will now have retrieved four items of data about the user without them having to enter those details again; by placing a call to this plug-in on each page where these details may be needed, you will always have access to them. The Plug-in function PIPHP_OpenSession() { if (!@session_start()) return array(FALSE); if (!isset($_SESSION['handle'])) return array(FALSE); C h a p t e r 9 : M y S Q L , S e s s i o n s , a n d C o o k i e s 225 C h a p t e r 9 : M y S Q L , S e s s i o n s , a n d C o o k i e s 225 $vars = array(); $vars[] = $_SESSION['handle']; $vars[] = $_SESSION['pass']; $vars[] = $_SESSION['name']; $vars[] = $_SESSION['email']; return array(TRUE, $vars); } Close Session When a user has finished with your web site, it’s a good idea to provide them with a logout button or link with which they can close the current session in order to prevent another user on their PC from coming back to it. With this plug-in you can not only close the session, but all associated data is also destroyed, leaving no potential security risk behind. Figure 9-7 shows the result of first opening a session with PIPHP_OpenSession(), and then closing it again. After closing it, you will not be able to open the session again since all its data was destroyed. Your only option is to create a new one. About the Plug-in This plug-in closes a previously created and/or opened PHP session and destroys any associated data. It does not require any arguments. Variables, Arrays, and Functions $_SESSION The PHP main session array which is reinitialized to an empty array to delete its data How It Works This plug-in ensures that any data stored in the PHP $_SESSION array is destroyed by reinitializing the array, which it does by assigning it the value array(). FIGURE 9-7 Closing a session will completely log a user out of your web site. 67 . shows data that has been saved in a session using the PHP program file plugin65. php, being fully recalled by calling up plugin66 .php. FIGURE 9-6 With this plug- in, a single function call will retrieve. referenced. The Plug- ins function PIPHP_SanitizeString($string) { $string = strip_tags($string); return htmlentities($string); } function PIPHP_MySQLSanitizeString($string) { if (get_magic_quotes_gpc()). (get_magic_quotes_gpc()) $string = stripslashes($string); $string = PIPHP_SanitizeString($string); return mysql_real_escape_string($string); } Create Session If you have a web site that a user can join, then