Chapter 16 . PHP Development 485 Encrypting a (Web hosting service)

Chapter 16 . PHP Development 485 Encrypting a username before returning it In this section, after the username and password have been validated, I create a couple of seemingly random strings for values to store in cookies later. The PHP function md5()is used twice. Because both the session ID and the username should be validated (I ll tell you why later), I d like to send a username. However, sending a plaintext username back to the browser is not such a good idea (from the standpoint of security and privacy). The md5()function to the rescue! The relevant code looks like this: # Create a pseudo-random session id. srand((double)microtime()*99999999); $id = md5(rand(0,9999999)); # Encrypt the username $encuser = md5($user); Clearing the memory associated with a result The next PHP MySQL function hasn t been used before in this chapter s examples: mysql_free_result(), which clears the memory associated with a result. Although technically it doesn t have to be used here, it does ensure that the value in $resultwill be clean and fresh and that s one less source of potential error. Caution Because the use of mysql_free_result()wipes the old result set out of mem ory, you can t glean any further information from the old result set! Make sure you have the information you need before you trash the old result set. Using mysql_free_result()can be a lifesaver if your system is operating near the limit of its resources and you have a huge result set that takes up too much memory. Here s what the code looks like: # Get rid of the result, so I can send another query mysql_free_result($result) or die ( An error was encountered ); Note the comment that lets the programmer know what s intended here (and consider it a reminder to cultivate good documentation habits). Next, a call to the PHP time() function gives me a current Unix/Linux timestampvalue (given as the number of seconds since the Epoch), and running the UPDATE statement sets the session ID in the user_table along with the timestamp. Here s the code: $time = time(); $query = UPDATE user_table SET session = $id ,timestamp = $time WHERE user = $user ; $result = mysql_query($query) or die ( UPDATE failed! ); Using a timestamp together with the session ID helps ensure that the session is relatively recent (which is important to establish, as I ll show you in the program to validate cookies).
Looking for affordable and reliable webhost to host and run your business application? Then look no more and go to servlet web hosting services.

Leave a Reply