Plug in PHP 100 POWER SOLUTIONS- P33 potx

5 345 0
Plug in PHP 100 POWER SOLUTIONS- P33 potx

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

Thông tin tài liệu

126 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 126 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 Those characters that do not match are placed in the array $matches by the function, and from there are placed in the string $caught, separated by a comma/space pair so that they can be added to an error message. The string variable $plural is then assigned the value “ is” if there is a single match, or “s are” if there is more than one. This is then used when constructing the error message so that it reads grammatically, using one or other of the forms (the value of $plural is shown in bold): “The following character is not allowed”; “The following characters are not allowed”. Then, a for loop is entered for iterating through all the characters in the variable $required, which can contain any or all of the letters a, l, u, d, w, or p, which stand for any letter, lowercase, uppercase, digit, word (any letter or number), or punctuation. Depending on which letter is being processed, the variable $regex is assigned the correct value to enable the following preg_match() call to ensure that at least one of that character type is included in the string. This feature is very useful in cases where a certain type of input is required such as a number, or maybe a password that must have at least one each of a letter, number, and punctuation character. As the variable’s name indicates, all characters in $required must exist in the string being validated. Therefore if any one of the types of characters described by $required is not encountered, another error message is added to the $error array. Finally, if $error has no messages in it, then no errors were encountered, so a single- element array containing the value TRUE is returned. Otherwise, a two-element array is returned, the first of which is the value FALSE, and the second is the array of error messages. How to Use It To validate a user-supplied string, call the PIPHP_ValidateText() function, giving it the string to validate and various parameters indicating which characters are both allowed and required. For example, to ensure that a string to be used for a password has one of each type of character—lowercase, uppercase, digit, and punctuation—and is at least 6 and no more than 16 characters long, you could use code such as the following, where $text is extracted from the form input password: echo "<form method='post' action='$_SERVER[PHP_SELF]'>"; echo "<input type='text' name='password' />"; echo "<input type='submit' /></form>"; if (isset($_POST['password'])) { $text = $_POST['password']; $allowed = "a-zA-Z0-9 !&*+=:;@~#"; $required = "ludp"; $result = PIPHP_ValidateText($text, 10, 16, $allowed, $required); if ($result[0] == FALSE) for ($j = 0 ; $j < count($result[1]) ; ++$j) echo $result[1][$j] . ".<br>"; else echo "Password validated"; } C h a p t e r 6 : F o r m s a n d U s e r I n p u t 127 C h a p t e r 6 : F o r m s a n d U s e r I n p u t 127 You may wish to save this file with a filename such as validate.php, then you can call it up in your browser and view the result of entering different values. A copy of this file is also in the plug-ins.zip file (in /6/validate.php), which is downloadable from the companion web site at pluginphp.com. In this code, the string variable $allowed sets the plug-in to accept any of the following: letters of any case, as well as digits, the space character, and any characters out of !&*+=:;@~ and #. The $required string simultaneously tells the plug-in that there must be at least one lowercase letter, one uppercase letter, one digit, and one punctuation character. Upon the function’s return, if the first element of the array $result is FALSE, then validation failed and so the strings in the array stored in the second element are displayed— they are the error messages returned by the plug-in. But if the first element is TRUE, validation succeeded. Here’s another example. Because $allowed may include regular expression operators such as \w, which means any letter or digit, or the _ character, you could use the plug-in to ensure that a username (determined by you), which should only include letters, digits, underlines, periods, and hyphens (and cannot be comprised only of punctuation), has been correctly entered, like this: $result = PIPHP_ValidateText($username, 4, 20, "\w\.\-", "a"); In this case, the $allowed argument of \w means “allow letters, digits, and the underline,” while \. and \- also allow the period and hyphen. The $required parameter of a ensures there is at least one letter, which can be of either case. The Plug-in function PIPHP_ValidateText($text, $minlength, $maxlength, $allowed, $required) { $len = strlen($text); $error = array(); if ($len < $minlength) $error[] = "The string length is too short " . "(min $minlength characters)"; elseif ($len > $maxlength) $error[] = "The string length is too long " . "(max $maxlength characters)"; $result = preg_match_all("/([^$allowed])/", $text, $matches); $caught = implode(array_unique($matches[1]), ', '); $plural = strlen($caught) > 1 ? $plural = "s are" : " is"; if ($result) $error[] = "The following character$plural " . "not allowed: " . $caught; for ($j = 0 ; $j < strlen($required) ; ++$j) { switch(substr(strtolower($required), $j, 1)) 128 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 128 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 { case "a": $regex = "a-zA-Z"; $str = "letter"; break; case "l": $regex = "a-z"; $str = "lower case"; break; case "u": $regex = "A-Z"; $str = "upper case"; break; case "d": $regex = "0-9"; $str = "digit"; break; case "w": $regex = "\w"; $str = "letter or number"; break; case "p": $regex = "\W"; $str = "punctuation"; break; } if (!preg_match("/[$regex]/", $text)) $error[] = "The string must include at least one " . "$str character"; } if (count($error)) return array(FALSE, $error); else return array(TRUE); } Validate E-mail Quite often people will make mistakes when entering their e-mail address into a web form. This is also another common area where some users just enter rubbish to see what happens. To catch these things, you can use this plug-in to at least check whether the format of an e-mail address supplied to you is valid, as shown in Figure 6-6. About the Plug-in This plug-in accepts an e-mail address whose format requires validating. On success, it returns TRUE, otherwise it returns FALSE. It takes this argument: • $email The e-mail address to be validated FIGURE 6-6 Using this plug-in you can ensure that the format of an e-mail address is valid. 36 C h a p t e r 6 : F o r m s a n d U s e r I n p u t 129 C h a p t e r 6 : F o r m s a n d U s e r I n p u t 129 Variables, Arrays, and Functions $at Integer pointing to the position of the @ sign $left String containing the left half of the e-mail address $right String containing the right half of the e-mail address $res1 Array result from validating $left $res2 Array result from validating $right PIPHP_ValidateText() Plug-in 35: function to validate a string How It Works The most obvious required part of an e-mail address is the @ symbol, so the first thing this plug-in does is locate its position and store it in the variable $at. If $at is given the value FALSE, or if the length of $email is less than the minimum of six characters that an e-mail address can have (a@b.cc), then the value FALSE is returned, because the address is already found to be invalid. Next the e-mail address is split into the two halves on either side of the position pointed to by $at using the substr() function. The left portion is assigned to the variable $left and the right to the variable $right. Then plug-in 35, PIPHP_ValidateText(), is called to evaluate each half. The left half must be between one and 64 characters in length and may comprise any letters, digits, underlines, periods, and + or - symbols. This is enforced using the argument of \w\.\+\ Also, at least one letter must be included, so the second argument of a checks for that. The right half of an e-mail address must be between one and 255 characters in length and may be comprised of any mix of letters, digits, hyphens, or periods. This validation is accomplished using the argument \a-zA-Z0-9\.\ And to ensure at least one letter appears in the domain, a second argument of a is supplied. The results of these two validations are placed in the arrays $res1 and $res2. Final validation is achieved by ensuring there is at least one period in the right half of the e-mail address and that both the previous two validations were also successful. If so, then TRUE is returned, otherwise FALSE is returned. How to Use It To validate an e-mail address, just pass it to PIPHP_ValidateEmail(), which will return TRUE if successful, otherwise it will return FALSE, like this: if (PIPHP_ValidateEmail($email)) echo "Validation succeeded"; Note that because this plug-in makes use of plug-in 35, PIPHP_ValidateText(), you must also have a copy of it in the same program file, or otherwise include it. The Plug-in function PIPHP_ValidateEmail($email) { $at = strrpos($email, '@'); if (!$at || strlen($email) < 3) return FALSE; 130 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 130 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 $left = substr($email, 0, $at); $right = substr($email, $at + 1); $res1 = PIPHP_ValidateText($left, 1, 64, "\w\.\+\-", "a"); $res2 = PIPHP_ValidateText($right, 1, 255, "\a-zA-Z0-9\.\-", "a"); if (!strpos($right, '.') || !$res1[0] || !$res2[0]) return FALSE; else return TRUE; } Spam Catch Even with a strong Captcha system in place, you will still find users trying to manually spam your web site. They tend to be people who discover your site through a very specific search engine query for which they would like their own site to also rank well, and they hope that by adding a link back to their site from yours this will happen. Using this plug-in you can specify a set of keywords that will trigger spam detection, and then use the level of spam certainty returned by the function to decide whether to ignore a user post. Figure 6-7 illustrates the plug-in in action. About the Plug-in This plug-in accepts a user-supplied string and matches it against a list of keywords to determine the likelihood that the string contains spam. It takes these arguments: • $text The e-mail address to be validated • $words An array of keywords against which to check Variables, Arrays, and Functions • None FIGURE 6-7 This plug-in will go a long way towards further reducing spam on your web site. 37 . illustrates the plug- in in action. About the Plug- in This plug- in accepts a user-supplied string and matches it against a list of keywords to determine the likelihood that the string contains spam that because this plug- in makes use of plug- in 35, PIPHP_ValidateText(), you must also have a copy of it in the same program file, or otherwise include it. The Plug- in function PIPHP_ValidateEmail($email). 129 Variables, Arrays, and Functions $at Integer pointing to the position of the @ sign $left String containing the left half of the e-mail address $right String containing the right half of the e-mail

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

Từ khóa liên quan

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

Tài liệu liên quan