PAGES THAT REMEMBER: SIMPLE LOGIN AND MULTIPAGE FORMS You need to get rid of the warning message in step 8, not only because it looks bad, but also because it means setcookie() can t invalidate the session cookie. Even though session_start() comes immediately after the opening PHP tag in session03.php, the warning message is triggered by the DOCTYPE declaration, the
, and other XHTML being output before setcookie(). Although you could put setcookie() in the PHP block above the DOCTYPE declaration, you would also need to assign the value of $_SESSION[’name’] to an ordinary variable, because it ceases to exist after the session is destroyed. Rather than pull the whole script apart, the answer is to buffer the output with ob_start(). PHP Solution 9-2: Buffering the output with ob_start() Continue working with session03.php from the previous section. 1. Amend the PHP block above the DOCTYPE declaration like this: This turns on output buffering and prevents output being sent to the browser until the end of the script, or until you specifically flush the output with ob_end_flush(). 2. Flush the output immediately after invalidating the session cookie like this: // invalidate the session cookie if (isset($_COOKIE[session_name()])) { setcookie(session_name(), ‘’, time()-86400, ‘/’); } ob_end_flush(); 3. Save session03.php and test the sequence again. This time, there should be no warning. More importantly, the session cookie will no longer be valid. As you have just seen, the combination of session variables and conditional statements lets you present completely different pages to a visitor depending on whether a session vari able has been set. All you need to do is add a password checking system, and you have a basic user authentication system. Using file-based authentication In PHP Solution 7-2, I showed you how to use the file() function to read each line of a text file into an array. You can now adapt that script to create a simple login system using sessions. Each person s username and password is separated by a comma and recorded on a new line of a text file like this: david, codeslave chris, bigboss I ll use the same text file as before: filetest03.txt, which is in the private folder that was set up in Chapter 7. Refer back to Chapter 7 if you haven t already set up a folder for PHP to read and write files. 241
If you are looking for affordable and reliable webhost to host and run your business application visit our
ftp web hosting services.