Archive for March, 2008

Web hosting billing - Chapter 16 . PHP Development 487 The check_sessionfunction

Monday, March 31st, 2008

Chapter 16 . PHP Development 487 The check_sessionfunction would normally be called from within another page. For example, I have a page called userpage.phpthat I do not want anyone to gain access to unless they are valid. Including a call to this function at the beginning of that page helps me ensure that the user has a valid cookie and is authorized to view the page. Validating the user and the cookie The query in the upcoming code snippet is the same one sent to actually validate the user and the cookie. $query = SELECT auth_group FROM user_table WHERE session = $cookie_session AND timestamp > (unix_timestamp() - 600) AND md5(user) = $cookie_user ; Here I m using the WHERE clause to look for three matches: . The session ID should match the one sent in the user cookie. . The timestamp in the user_tableis compared to the current time. If the timestamp is less than 10 minutes ago (600 seconds), then it s valid. . The user in the table (sent through md5) should match the md5ed user from the cookie. If all three of these values match appropriately, the cookie is valid. Using three values in the database to validate cookies makes it more difficult for a malicious user to fake a session ID to try to gain access to protected resources. Even if a user can fake a session ID, he or she must tie in that session ID with the encrypted username within the time specified in the query (in this case, 10 minutes). The function ends with a call to the PHP return() function. The function sends the value back to the calling program. return $row[ auth_group ]; As an example, here s the code that creates a page called userpage.php. That page calls the check_sessionfunction to validate the user before continuing. The code for the page is as follows: We recommend you use shared web hosting services, because many users agree that it is cheap, reliable and customer-satisfying webhost.

486 Part IV . Development Setting (Web site designers) and validating

Sunday, March 30th, 2008

486 Part IV . Development Setting and validating the cookie The following code contains two examples of the setcookie() function: setcookie( cookie_session , $id ,time()+60, / , ,0); setcookie( cookie_user , $encuser ,time()+60, / , ,0); print You have been successfully logged in

; The print statement at the end of this code snippet would be a good place to send a redirect to the client, sending it to another page or calling another function. Note In the first code snippet just given, normally you d put the valid URL for the cookie between the final double quotes to the left of the 0 in both instances. As it happens, some crazy redirection on my network prevents me from placing that value correctly (within that final set of quotes) for the example. The program to validate cookies is as follows: (unix_timestamp() - 600) AND md5(user) = $cookie_user ; $result = mysql_query($query) or die ( Query failed ); $num = mysql_num_rows($result); if ($num == 0) { print Session has expired

n ; exit; } else { $row = mysql_fetch_array($result); return $row[ auth_group ]; } } # End function check_session ?>
From our experience, we can recommend PHP Web Hosting services, if you need affordable webhost to host and run your web application.

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

Saturday, March 29th, 2008

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.

484 Part IV . Development } function authenticate($user,$pass)

Saturday, March 29th, 2008

484 Part IV . Development } function authenticate($user,$pass) { # This subroutine looks up the grants for the given # user/host pair. $query = SELECT session FROM user_table WHERE user = $user AND pass = password( $pass ) ; $result = mysql_query($query) or die ( Query failed ); $num = mysql_num_rows($result); if ($num == 0) { print Username and/or password incorrect

n ; exit; } else { $row = mysql_fetch_array($result); # Create a pseudo-random session id. srand((double)microtime()*99999999); $id = md5(rand(0,9999999)); # Encrypt the username $encuser = md5($user); # Get rid of the result, so I can send another query mysql_free_result($result) or die ( An error was encountered ); $time = time(); $query = UPDATE user_table SET session = $id ,timestamp = $time WHERE user = $user ; $result = mysql_query($query) or die ( UPDATE failed! ); setcookie( cookie_session , $id ,time()+60, / , ,0); setcookie( cookie_user , $encuser ,time()+60, / , ,0); print You have been successfully logged in

; } } # End function authenticate ?> Examination of the code reveals that many of the functions (and some of the logic) previously discussed in this chapter are incorporated into the program. A couple of snippets call for a closer look: One encrypts an otherwise-plaintext username before returning it to the browser; the other clears the memory associated with a result.
We recommend you use shared web hosting services, because many users agree that it is cheap, reliable and customer-satisfying webhost.

Ftp web hosting - Chapter 16 . PHP Development 483 Two main

Friday, March 28th, 2008

Chapter 16 . PHP Development 483 Two main PHP scripts make up the authentication system: a sign-in program and a cookie-validation program. The sign-in program prints a form for username and password, and then sets the cookie. It looks like this:

; echo Enter Username:

n ; echo Enter Password:

n ; echo

n ; echo

n ; exit; } elseif (!isset($user)) { echo Please enter username

n ; echo

; echo Enter Username:

n ; echo Enter Password:

n ; echo

n ; echo

n ; exit; } elseif (!isset($pass)) { echo Please enter password

n ; echo

; echo Enter Username:

n ; echo Enter Password:

n ; echo

n ; echo

n ; exit; } else { # Connect to the database $dbconn = mysql_connect($host,$username,$password) or die ( Couldn t connect to database server ); $db = mysql_select_db( auth ); $quoteduser = mysql_escape_string($user); $quotedpass = mysql_escape_string($pass); authenticate($user,$pass);
Looking for affordable and reliable webhost to host and run your business application? Then look no more and go to servlet web hosting services.

482 Part IV . Development Throughout the program,

Thursday, March 27th, 2008

482 Part IV . Development Throughout the program, the persistent challenge is to keep track of both the similarities and the significant differences between Perl and PHP to avoid losing functionality. Cookies with no milk Cookies are value-plus-parameter pairs stored in the HTTP header and sent to a Web agent (such as a browser) when retrieving an object usually a Web page from the Internet. They are commonly used to store user-related data (such as session identifiers) and can be set to expire at a point in the future determined by the site that sets and uses the cookie. Although PHP includes functions for setting and easily retrieving cookies, it also includes other functions for setting and retrieving session identifiers; some of these don t use cookies. A developer can use either a cookie function or a session function in PHP to maintain state or authenticate users for Web pages. There are probably endless methods for creating authentication mechanisms for Web sites and Web pages. This section examines one method for authenticating users that also sets a cookie with a session identifier. The approach that is specifically relevant to this book is to integrate the authentication mechanism with a MySQL database. Once that integration is complete, visitors can enter a username and password. The credentials will be authenticated against data in a MySQL database. If the login is successful, a session ID and timestamp are recorded in the MySQL database. A cookie is sent to the user upon success, containing that same session ID and user- name (in encrypted form). When the user attempts to access another resource within the site, the user s cookie is examined and compared to the one in the database. If it s valid, the user is allowed to access the resource. In addition, the database includes a group function so resources can be limited by group (should the need arise). No need to undertake full normalization of the database for this site. Since the site is intended for low usage, normalization would have little or no effect on performance. The first step toward the authentication system is to create the database in effect, a big table with some special features. The table for the authentication system has the following structure: CREATE TABLE `user_table` ( `user` varchar(20) NOT NULL default , `pass` varchar(20) default NULL, `session` varchar(50) default NULL, `auth_group` varchar(20) default NULL, `timestamp` varchar(32) default NULL, PRIMARY KEY (`user`) Note
Check Tomcat Web Hosting services for best quality webspace to host your web application.

Chapter 16 . PHP Development 481 In addition (Web hosting top)

Wednesday, March 26th, 2008

Chapter 16 . PHP Development 481 In addition to the functions used in this section, another method is possible for processing the returned results. It looks like this: else { # User wants to simply lookup the hosts allowed # for given username. # Make sure the username is safe to # send to MySQL. $quoteduser = mysql_escape_string($user); $query = SELECT host,user FROM user WHERE user = $quoteduser ; $result = mysql_query($query) or die ( Cannot execute query 1 ); while ( $row = mysql_fetch_array($result) ) { echo User . $row[ user ] . is allowed to connect from: . $row[ host ] .

; } } The final section of the program is called when an @ symbol is included in the input that comes from the form: function priv($user,$inhost) { # This subroutine looks up the grants for the given # user/host pair. $query = SHOW GRANTS FOR $user $inhost ; $result = mysql_query($query); $i = 0; if (! $result) { print No such grant

n ; } else { while ($grant = mysql_fetch_array($result) ) { print $grant[$i]

; $i++; } } } ?> In the code snippet just given, notice that PHP calls the function with the name function (whereas Perl uses subto designate a user-defined function). The function also uses a different method for receiving the variables that are called with it.
If you are looking for affordable and reliable webhost to host and run your business application visit our ftp web hosting services.

480 Part IV (Mac os x web server) . Development HTML directly in

Tuesday, March 25th, 2008

480 Part IV . Development HTML directly in the PHP program. In this instance, if the Submit button isn t clicked (as it would be when you initially visit the page, or if the userfield were blank), the page is simply served again. if ((! $submit) || (! $user)) { echo

; echo Enter Username:

n ; echo

n ; echo

n ; exit; } The PHP method for connecting to the database server and database is next in the script: # Connect to the database $dbconn = mysql_connect($host,$username,$password) or die ( Couldn t connect to database server ); $db = mysql_select_db( mysql ); The next bit of code examines the value that was input, looking for an @ symbol (which would indicate that the query is looking for the grants privileges afforded a given user). Notice the use of the PHP ereg function to examine the $user string variable. A PHP MySQL function introduced in this section mysql_escape_string() works somewhat like the mysql_quote() function in Perl. The mysql_escape_string()function takes a string that was already input and makes it safe for use in a MySQL statement. The mysql_quote()function in Perl does the same thing, but it puts quotation marks around the string which the mysql_escape_string()function in PHP does not. Therefore, to use mysql_escape_string(), put quotes around the string in your PHP MySQL statements. The following snippet is an example: # If there s an @ symbol then the user wants to look up # grants. if (ereg( @ , $user)) { list ($user,$inhost) = split( @ , $user); # Make sure the username and host are safe to # send to MySQL. $quoteduser = mysql_escape_string($user); $quotedhost = mysql_escape_string($inhost); priv($user,$inhost); } The next section is executed when no @ symbol is included from the form (hence, in effect, no grants are sought). The program queries for the already-input username and returns the result.
If you are in need for chaep and reliable webhost to host your website, our recommendation is http web server services.

Web hosting faq - Chapter 16 . PHP Development 479 Figure 16-21:

Monday, March 24th, 2008

Chapter 16 . PHP Development 479 Figure 16-21: Querying for privileges works the same with the PHP version as with the Perl CGI version. Examination of the PHP version of the user manager Many of the user manager s basic functions are the same in both the Perl and PHP versions in particular, functions such as whileand if. Looking at the first bits of the PHP code, notice that the program no longer starts with #!/usr/bin/perl (which makes sense, since this PHP version isn t a Perl program). An include statement in the PHP code includes the database credentials; it s the last line of the following code snippet: We would like to recommend you tested and proved virtual web hosting services, which you will surely find to be of great quality.

478 Part IV . Development Figure 16-19: The

Sunday, March 23rd, 2008

478 Part IV . Development Figure 16-19: The results with the PHP version of the user manager look the same as those from the Perl CGI version. Figure 16-20: The privilege lookup with the PHP version of the user manager
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.