Plug in PHP 100 POWER SOLUTIONS- P51 doc

5 117 0
Plug in PHP 100 POWER SOLUTIONS- P51 doc

Đang tải... (xem toàn văn)

Thông tin tài liệu

216 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 216 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 therefore have to provide these details to your program so it can connect to MySQL and select the database. You can do this with the following code: $dbhost = 'localhost'; $dbname = 'piphp'; $dbuser = 'testing'; $dbpass = 'testing'; mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error()); mysql_select_db($dbname) or die(mysql_error()); These six lines define the database host and name, as well as a MySQL username and password, connect to MySQL, and select the database. If any errors occur in this process, program execution is terminated and an error message is displayed. On a production server, you may wish to replace the calls to the die() function with your own more user-friendly error handling. Next you need to define the table name and the handle of the user whose details you wish to look up, and then call the plug-in, like this: $table = 'Users'; $handle = 'firstprez'; $result = PIPHP_GetUserFromDB($table, $handle); After the call, if $result[0] is FALSE, then the lookup failed and no matching user was found, otherwise $result[0] will have a value of TRUE and $result[1] will contain a sub-array with the user’s details, which you can access using code such as this: if ($result[0] == FALSE) echo "Lookup failed."; else echo "Name = " . $result[1][0] . "<br />" . "Handle = " . $result[1][1] . "<br />" . "Pass(salted) = " . $result[1][2] . "<br />" . "Email = " . $result[1][3]; The Plug-in function PIPHP_GetUserFromDB($table, $handle) { $query = "SELECT * FROM $table WHERE handle='$handle'"; $result = mysql_query($query); if (mysql_num_rows($result) == 0) return array(FALSE); else return array(TRUE, mysql_fetch_array($result, MYSQL_NUM)); } Verify User in DB Using this plug-in, you can pass a username (handle) and password, as entered by a user and, without needing to look up any details, just pass these on to the plug-in, which will then report whether they verify or not. In Figure 9-3 the handle firstprez is checked against two similar but different passwords. Only the correct one of GW022232 verifies. Incidentally, GW022232 is not a very secure password, and the user would be well advised not to use his birthday of February 22nd ‘32 in future passwords. 63 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 217 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 217 About the Plug-in This plug-in compares a supplied handle (username) and password to those stored in the database. If they match, it returns TRUE; otherwise, it returns FALSE. It requires these arguments: • $table The name of the data table • $salt1 The first salt as supplied to PIPHP_AddUserToDB() • $salt2 The second salt value • $handle The user’s username as entered by them • $pass The user’s password Variables, Arrays, and Functions $result Array result of calling PIPHP_GetUserFromDB() How It Works This function takes the handle supplied to it, which will in turn have been provided by a user, and passes it to the PIPHP_GetUserFromDB() plug-in to retrieve the accompanying user details from the database. If the call fails, signified by the return value $result[0] having a value of FALSE, then the handle in $handle was not found in the database. Otherwise, the value in $result[1][2], which is the stored salted and md5() processed password, is compared with the result of performing the identical salting and md5() transformation on the supplied password. If the results are the same, then the password supplied is the same as the one originally used to create the account, and so a value of TRUE is returned. Otherwise, FALSE is returned. How to Use It To use this plug-in you need to have opened a connection to MySQL and selected the database to use, with code such as this: $dbhost = 'localhost'; $dbname = 'piphp'; $dbuser = 'testing'; FIGURE 9-3 A username (handle) and password must match exactly to be verified. 218 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 218 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 $dbpass = 'testing'; mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error()); mysql_select_db($dbname) or die(mysql_error()); In the preceding, $dbhost is likely to remain with a value of localhost since the web server and PHP processor will be running on the same computer as the MySQL database. The variable $dbname is the database you should have created, as advised in plug-in 61, Add User to DB. The variables $dbuser and $dbpass should be the username and password of a MySQL user that has been granted access to the database. The remaining two lines connect to MySQL and select the database. If either action fails, an error message is displayed and program execution stops. Therefore, on a production server, you may wish to replace the die() call with an error handling function of your own. Next you need to assign values for the table and two salts used, as well as the handle and password to be verified, like this: $table = 'Users'; $salt1 = "F^&£g"; $salt2 = "9*hz!"; $handle = 'firstprez'; $pass = 'GW022231'; The two salts, $salt1 and $salt2, must be the same semi-random strings you assigned when using PIPHP_AddUSerToDB(). You are now ready to verify the user’s details in the following way: $result = PIPHP_VerifyUserInDB($table, $salt1, $salt2, $handle, $pass); Upon success, $result will have the value TRUE, otherwise it will be FALSE. You can use this return value in the following manner: if ($result) echo "Login details $handle/$pass verified."; else echo "Login details $handle/$pass could not be verified."; Other than for testing the plug-in, this code isn’t actually useful. Instead, your code will likely re-present a form to the user if verification failed; otherwise, it will probably log a user in, possibly using PHP sessions, described a little later on in this chapter, starting with plug-in 65, Create Session. Incidentally, if you entered the details for this sample user earlier on in this chapter, this example will not verify unless you change the password from GW022231 to GW022232. The Plug-in function PIPHP_VerifyUserInDB($table, $salt1, $salt2, $handle, $pass) { $result = PIPHP_GetUserFromDB($table, $handle); if ($result[0] == FALSE) return FALSE; elseif ($result[1][2] == md5($salt1 . $pass . $salt2)) return TRUE; else return 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 219 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 219 Sanitize String and MySQL Sanitize String When accepting user input for redisplay, and particularly if it will be inserted into a database, it’s important that you sanitize the input to remove any malicious attempts at hijacking your server, or otherwise injecting unwanted MySQL commands, HTML, or JavaScript. Figure 9-4 shows each of the plug-ins in this section being used to sanitize a string. The function PIPHP_ SanitizeString() has removed the HTML <b> and </b> tags from the string and converted the & symbol to the &amp; HTML entity, while PIPHP_MySQLSanitizeString() has also added escape characters before the single quotation marks, so that they will be inserted into a field by MySQL rather than possibly being interpreted. About the Plug-ins These plug-ins take a string and sanitize it for reuse on your web site and/or in a MySQL database. They require this argument: • $string A string to be sanitized Variables, Arrays, and Functions PIPHP_SanitizeString() The function PIPHP_MySQLSanitizeString calls the function PIPHP_SanitizeString() to prevent code duplication How They Work Let’s start with the PIPHP_SanitizeString() function, which calls two PHP functions: strip_tags() and htmlentities(). The former removes all HTML tags from a string, while the latter converts all instances of characters such as < and > to &lt; and &gt;, & to &amp;, and so on. Between them they will remove any attempts at inserting any HTML tags into your web site, whether they are simple tags such as <b> for bold or more dangerous <script> tags. They also see to it that no special characters are allowed by replacing them with HTML entities that will not perform an action, but only display in a browser as the characters they represent. FIGURE 9-4 This pair of plug-ins will protect your web site from hacking attempts. 64 220 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 220 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 Calling the PIPHP_MySQLSanitizeString() function does the same as calling the PIPHP_SanitizeString() function, but in addition it deals with potential problems relating to MySQL. First, it checks whether the Magic Quotes setting of PHP is enabled, which is a method of dealing with quotation marks supplied by the user. When Magic Quotes is on, all single- and double-quote characters, as well as backslashes and NULL characters are escaped automatically by preceding them with a backslash. However, the feature is now deprecated and should not be used as there are better ways of sanitizing data (such as using the two plug-ins presented in this section). Therefore, if Magic Quotes is enabled, then the first thing this plug-in does is call the stripslashes() function to remove any that may have been added. Next it calls the PIPHP_ SanitizeString() function, and finally it calls the mysql_real_escape_string() function, which renders a string totally harmless to MySQL injection attacks. These attacks occur when a malicious user enters a quotation mark in the hope that it will close a MySQL statement, enabling MySQL commands they add after the quote to be executed. For example, the following MySQL command, resulting from a user having entered the handle jjones, looks quite safe: SELECT * FROM Users WHERE handle='jjones' AND pass='secret'; But what if, when asked for their handle, a user were to input a value of Admin'# and it wasn’t sanitized? Well, if this string were allowed through to MySQL, the complete command would become: SELECT * FROM Users WHERE handle='Admin'#' AND pass='secret'; What has happened here is that the user closed the quotation mark and then supplied a # symbol, which is treated by MySQL as the start of a comment. Therefore everything from the # onwards (highlighted in the preceding code in italics) gets ignored and so users find themselves logged in as the user Admin. Obviously this is not good, to say the least. However, a simple call to mysql_real_escape_string() replaces all such possible hacks with escaped versions of the characters, so that the string can only ever be used as data and never treated as a command to be executed. Combining all these security measures into these new functions ensures you never forget any when coding your web sites. How to Use Them To use either of these functions, simply call them up by passing a string to be sanitized, like this: $string = "& This is an 'example' string to be <b>sanitized</b>"; echo "Using Sanitize String<xmp>"; echo "Before: " . $string . "\n"; echo "After: " . PIPHP_SanitizeString($string); echo "</xmp>"; $dbhost = 'localhost'; $dbname = 'piphp'; $dbuser = 'testing'; $dbpass = 'testing'; mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error()); . characters before the single quotation marks, so that they will be inserted into a field by MySQL rather than possibly being interpreted. About the Plug- ins These plug- ins take a string and sanitize. hijacking your server, or otherwise injecting unwanted MySQL commands, HTML, or JavaScript. Figure 9-4 shows each of the plug- ins in this section being used to sanitize a string. The function PIPHP_ SanitizeString(). 219 Sanitize String and MySQL Sanitize String When accepting user input for redisplay, and particularly if it will be inserted into a database, it’s important that you sanitize the input to remove

Ngày đăng: 07/07/2014, 08:20

Mục lục

  • Contents

  • Acknowledgments

  • Introduction

  • 1 Building a Development Server

    • Windows XP, Windows Vista, and Windows 7

      • Reinstalling Zend Server CE

      • Upgrading Zend Server CE

      • Windows Security Alerts

      • After Installation

      • Uninstalling

      • Document Root

      • Ubuntu and Debian Linux

        • Uninstalling

        • After Installation

        • Document Root

        • Fedora, RHEL, and CentOS Linux

          • Installing MySQL

          • Uninstalling

          • Document Root

          • Other Versions of Linux

            • Installing MySQL

            • Uninstalling

            • Document Root

            • Mac OS X 10.4 Plus on Intel Chips

              • Document Root

              • Uninstalling

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan