Chinaunix首页 | 论坛 | 博客
  • 博客访问: 589931
  • 博文数量: 207
  • 博客积分: 10128
  • 博客等级: 上将
  • 技术积分: 2440
  • 用 户 组: 普通用户
  • 注册时间: 2004-10-10 21:40
文章分类

全部博文(207)

文章存档

2009年(200)

2008年(7)

我的朋友

分类:

2009-03-28 15:24:26

最近开始学 PHP,转篇不错的文章
 

by Chris Shiflett and Sean Coates

This article is a rebuttal to — henceforth referred to as the previous article — published last November here on Smashing Magazine. The introduction sounds intriguing:

Listed below are 10 excellent techniques that PHP developers should learn and use every time they program.

Unfortunately, the intrigue devolves into disappointment. We disagree with many of the tips, and even when we don’t, the accompanying explanation is weak or misleading. In this article, we go through each and every tip from the previous article and provide our own commentary and evidence, either to validate and clarify the tip, or to refute it. Our hope is that you don’t just accept our opinion, but rather learn enough to form your own.

1. Use an SQL Injection Cheat Sheet

This particular tip is just a link to a useful resource with no discussion on how to use it. Studying various permutations of one specific attack can be useful, but your time is better spent learning how to safeguard against it. Additionally, there is much more to Web app security than SQL injection. and , for example, are at least as common and at least as dangerous.

We can provide some much-needed context, but because we don’t want to focus too much on one attack, we’ll first take a step back. Every developer should be familiar with good security practices, and apps should be designed with these practices in mind. A fundamental rule is to never trust data you receive from somewhere else. Another rule is to escape data before you send it somewhere else. Combined, these rules can be simplified to make up a basic tenet of security: filter input, escape output (FIEO).

The root cause of SQL injection is a failure to escape output. More specifically, it is when the distinction between the format of an SQL query and the data used by the SQL query is not carefully maintained. This is common in PHP apps that construct queries as follows:

  1.   
  2. $query = "SELECT *   
  3.           FROM   users   
  4.           WHERE  name = '{$_GET['name']}'";   
  5.   
  6. ?>  

In this case, the value of $_GET['name'] is provided by another source, the user, but it is neither filtered nor escaped.

Escaping preserves data in a new context. The emphasis on escaping output is a reminder that data used outside of your Web app needs to be escaped, else it might be misinterpreted. By contrast, filtering ensures that data is valid before it’s used. The emphasis on filtering input is a reminder that data originating outside of your Web app needs to be filtered, because it cannot be trusted.

Assuming we’re using MySQL, the SQL injection vulnerability can be mitigated by escaping the name with mysql_real_escape_string(). If the name is also filtered, there is an additional layer of security. (Implementing multiple layers of security is called “defense in depth” and is a very good security practice.) The following example demonstrates filtering input and escaping output, with naming conventions used for code clarity:

  1.   
  2. // Initialize arrays for filtered and escaped data, respectively.   
  3. $clean = array();   
  4. $sql = array();   
  5.   
  6. // Filter the name. (For simplicity, we require alphabetic names.)   
  7. if (ctype_alpha($_GET['name'])) {   
  8.     $clean['name'] = $_GET['name'];   
  9. else {   
  10.     // The name is invalid. Do something here.   
  11. }   
  12.   
  13. // Escape the name.   
  14. $sql['name'] = mysql_real_escape_string($clean['name']);    
  15.   
  16. // Construct the query.   
  17. $query = "SELECT *   
  18.           FROM   users   
  19.           WHERE  name = '{$sql['name']}'";   
  20.   
  21. ?>  

Although the use of naming conventions can help you keep up with what has and hasn’t been filtered, as well as what has and hasn’t been escaped, a much better approach is to use prepared statements. Luckily, with PDO, PHP developers have a universal API for data access that supports prepared statements, even if the underlying database does not.

Remember, SQL injection vulnerabilities exist when the distinction between the format of an SQL query and the data used by the SQL query is not carefully maintained. With prepared statements, you can push this responsibility to the database by providing the query format and data in distinct steps:

  1.   
  2. // Provide the query format.   
  3. $query = $db->prepare('SELECT *   
  4.                        FROM   users   
  5.                        WHERE  name = :name');   
  6.   
  7. // Provide the query data and execute the query.   
  8. $query->execute(array('name' => $clean['name']));   
  9.   
  10. ?>  

The provides more information and examples. Prepared statements offer the strongest protection against SQL injection.

2. Know the Difference Between Comparison Operators

This is a good tip, but it is missing a practical example that demonstrates when a non-strict comparison can cause problems.

If you use strpos() to determine whether a substring exists within a string (it returns FALSE if the substring is not found), the results can be misleading:

  1.   
  2. $authors = 'Chris & Sean';   
  3.   
  4. if (strpos($authors'Chris')) {   
  5.     echo 'Chris is an author.';   
  6. else {   
  7.     echo 'Chris is not an author.';   
  8. }   
  9.   
  10. ?>  

Because the substring Chris occurs at the very beginning of Chris & Sean, strpos() correctly returns 0, indicating the first position in the string. Because the conditional statement treats this as a Boolean, it evaluates to FALSE, and the condition fails. In other words, it looks like Chris is not an author, but he is!

This can be corrected with a strict comparison:

  1.   
  2. if (strpos($authors'Chris') !== FALSE) {   
  3.     echo 'Chris is an author.';   
  4. else {   
  5.     echo 'Chris is not an author.';   
  6. }   
  7.   
  8. ?>  

3. Shortcut the else

This tip accidentally stumbles upon a useful practice, which is to always initialize variables before you use them. Consider a conditional statement that determines whether a user is an administrator based on the username:

  1.   
  2. if (auth($username) == 'admin') {   
  3.     $admin = TRUE;   
  4. else {   
  5.     $admin = FALSE;   
  6. }   
  7.   
  8. ?>  

This seems safe enough, because it’s easy to comprehend at a glance. Imagine a slightly more elaborate example that sets variables for name and email as well, for convenience:

  1.   
  2. if (auth($username) == 'admin') {   
  3.     $name = 'Administrator';   
  4.     $email = 'admin@example.org';   
  5.     $admin = TRUE;   
  6. else {   
  7.     /* Get the name and email from the database. */  
  8.     $query = $db->prepare('SELECT name, email   
  9.                            FROM   users   
  10.                            WHERE  username = :username');   
  11.     $query->execute(array('username' => $clean['username']));   
  12.     $result = $query->fetch(PDO::FETCH_ASSOC);   
  13.     $name = $result['name'];   
  14.     $email = $result['email'];   
  15.     $admin = FALSE;   
  16. }   
  17.   
  18. ?>  

Because $admin is still always explicitly set to either TRUE or FALSE, all is well, but if a developer later adds an elseif, there’s an opportunity to forget:

  1.   
  2. if (auth($username) == 'admin') {   
  3.     $name = 'Administrator';   
  4.     $email = 'admin@example.org';   
  5.     $admin = TRUE;   
  6. elseif (auth($username) == 'mod') {   
  7.     $name = 'Moderator';   
  8.     $email = 'mod@example.org';   
  9.     $moderator = TRUE;   
  10. else {   
  11.     /* Get the name and email. */  
  12.     $query = $db->prepare('SELECT name, email   
  13.                            FROM   users   
  14.                            WHERE  username = :username');   
  15.     $query->execute(array('username' => $clean['username']));   
  16.     $result = $query->fetch(PDO::FETCH_ASSOC);   
  17.     $name = $result['name'];   
  18.     $email = $result['email'];   
  19.     $admin = FALSE;   
  20.     $moderator = FALSE;   
  21. }   
  22.   
  23. ?>  

If a user provides a username that triggers the elseif condition, $admin is not initialized. This can lead to unwanted behavior, or worse, a security vulnerability. Additionally, a similar situation now exists for $moderator, which is not initialized in the first condition.

By first initializing $admin and $moderator, it’s easy to avoid this scenario altogether:

  1.   
  2. $admin = FALSE;   
  3. $moderator = FALSE;   
  4.   
  5. if (auth($username) == 'admin') {   
  6.     $name = 'Administrator';   
  7.     $email = 'admin@example.org';   
  8.     $admin = TRUE;   
  9. elseif (auth($username) == 'mod') {   
  10.     $name = 'Moderator';   
  11.     $email = 'mod@example.org';   
  12.     $moderator = TRUE;   
  13. else {   
  14.     /* Get the name and email. */  
  15.     $query = $db->prepare('SELECT name, email   
  16.                            FROM   users   
  17.                            WHERE  username = :username');   
  18.     $query->execute(array('username' => $clean['username']));   
  19.     $result = $query->fetch(PDO::FETCH_ASSOC);   
  20.     $name = $result['name'];   
  21.     $email = $result['email'];   
  22. }   
  23.   
  24. ?>  

Regardless of what the rest of the code does, it’s now clear that $admin is FALSE unless it is explicitly set to something else, and the same is true for $moderator. This also hints at another good security practice, which is to fail safely. The worst that can happen as a result of not modifying $admin or $moderator in any of the conditions is that someone who is an administrator or moderator is not treated as one.

If you want to shortcut something, and you’re feeling a little disappointed that our example includes an else, we have a bonus tip that might interest you. We’re not certain it can be considered a shortcut, but we hope it’s helpful nonetheless.

Consider a function that determines whether a user is authorized to view a particular page:

  1.   
  2. function authorized($username$page) {   
  3.     if (!isBlacklisted($username)) {   
  4.         if (isAdmin($username)) {   
  5.             return TRUE;   
  6.         } elseif (isAllowed($username$page)) {   
  7.             return TRUE;   
  8.         } else {   
  9.             return FALSE;   
  10.         }   
  11.     } else {   
  12.         return FALSE;   
  13.     }   
  14. }   
  15.   
  16. ?>  

This example is actually pretty simple, because there are only three rules to consider: administrators are always allowed access; those who are blacklisted are never allowed access; and isAllowed() determines whether anyone else has access. (A special case exists when an administrator is blacklisted, but that is an unlikely possibility, so we’re ignoring it here.) We use functions for the rules to keep the code simple and to focus on the logical structure.

There are numerous ways this example can be improved. If you want to reduce the number of lines, a compound conditional can help:

  1.   
  2. function authorized($username$page) {   
  3.     if (!isBlacklisted($username)) {   
  4.         if (isAdmin($username) || isAllowed($username$page)) {   
  5.             return TRUE;   
  6.         } else {   
  7.             return FALSE;   
  8.         }   
  9.     } else {   
  10.         return FALSE;   
  11.     }   
  12. }   
  13.   
  14. ?>  

In fact, you can reduce the entire function to a single compound conditional:

  1.   
  2. function authorized($username$page) {   
  3.     if (!isBlacklisted($username) && (isAdmin($username) || isAllowed($username$page)) {   
  4.         return TRUE;   
  5.     } else {   
  6.         return FALSE;   
  7.     }   
  8. }   
  9.   
  10. ?>  

Finally, this can be reduced to a single return:

  1.   
  2. function authorized($username$page) {   
  3.     return (!isBlacklisted($username) && (isAdmin($username) || isAllowed($username$page));   
  4. }   
  5.   
  6. ?>  

If your goal is to reduce the number of lines, you’re done. However, note that we’re using isBlacklisted(), isAdmin(), and isAllowed() as placeholders. Depending on what’s involved in making these determinations, reducing everything to a compound conditional may not be as attractive.

This brings us to our tip. A return immediately exits the function, so if you return as soon as possible, you can express these rules very simply:

  1.   
  2. function authorized($username$page) {   
  3.   
  4.     if (isBlacklisted($username)) {   
  5.         return FALSE;   
  6.     }   
  7.   
  8.     if (isAdmin($username)) {   
  9.         return TRUE;   
  10.     }   
  11.   
  12.     return isAllowed($username$page);   
  13. }   
  14.   
  15. ?>  

This uses more lines of code, but it’s very simple and unimpressive (we’re proudest of our code when it’s the least impressive). More importantly, this approach reduces the amount of context you must keep up with. For example, as soon as you’ve determined whether the user is blacklisted, you can safely forget about it. This is particularly helpful when your logic is more complicated.

4. Drop Those Brackets

Based on the content of this tip, we believe the author means “braces,” not brackets. “Curly brackets” may mean braces to some, but “brackets” universally means “square brackets.”

This tip should be unconditionally ignored. Without braces, readability and maintainability are damaged. Consider a simple example:

  1.   
  2. if (date('d M') == '21 May')   
  3.     $birthdays = array('Al Franken',   
  4.                        'Chris Shiflett',   
  5.                        'Chris Wallace',   
  6.                        'Lawrence Tureaud');   
  7.   
  8. ?>  

If you’re good enough, smart enough, secure enough, notorious enough, or pitied enough, you might want to party on the 21st of May:

  1.   
  2. if (date('d M') == '21 May')   
  3.     $birthdays = array('Al Franken',   
  4.                        'Chris Shiflett',   
  5.                        'Chris Wallace',   
  6.                        'Lawrence Tureaud');   
  7.     party(TRUE);   
  8.   
  9. ?>  

Without braces, this simple addition causes you to party every day. Perhaps you have the stamina for it, so the mistake is a welcome one. Hopefully, the silly example doesn’t detract from the point, which is that the excessive partying is an unintended side effect.

In order to promote the practice of dropping braces, the previous article uses short examples such as the following:

  1.   
  2. if ($gollum == 'halfling'$height --;   
  3. else $height ++;   
  4.   
  5. ?>  

Because each condition is constrained to a single line, such mistakes might be less likely, but this leads to another problem: inconsistencies are jarring and require more time to read and comprehend. Consistency is such a valued quality that developers often abide by a coding standard even if they dislike the coding standard itself.

We recommend always using braces:

  1.   
  2. if (date('d M') == '21 May') {   
  3.     $birthdays = array('Al Franken',   
  4.                        'Chris Shiflett',   
  5.                        'Chris Wallace',   
  6.                        'Lawrence Tureaud');   
  7.     party(TRUE);   
  8. }   
  9.   
  10. ?>   
  11.    

You’re welcome to party every day, but make sure it’s deliberate, and please be sure to invite us!

5. Favor str_replace() Over ereg_replace() and preg_replace()

We hate to sound disparaging, but this tip demonstrates the sort of misunderstanding that leads to the same misuse it’s trying to prevent. It’s an obvious truth that string functions are faster at string matching than regular expression functions, but the author’s attempt to draw a corollary from this fails miserably:

If you’re using regular expressions, then ereg_replace() and preg_replace() will be much faster than str_replace().

Because str_replace() does not support pattern matching, this statement makes no sense. The choice between string functions and regular expression functions comes down to which is fit for purpose, not which is faster. If you need to match a pattern, use a regular expression function. If you need to match a string, use a string function.

6. Use Ternary Operators

The benefit of the ternary operator is debatable (there’s only one, by the way). Here is a line of code from an audit we performed recently:

  1.   
  2. $host = strlen($host) > 0 ? $host : htmlentities($host);   
  3.   
  4. ?>  

Oops! The author actually means to escape $host if the string length is greater than zero, but instead accidentally does the opposite. Easy mistake to make? Maybe. Easy to miss during a code audit? Certainly. Concision doesn’t necessarily make the code any better.

The ternary operator may be fine for one-liners, prototypes, and templates, but we strongly believe that an ordinary conditional statement is almost always better. PHP is descriptive and verbose. We think code should be, too.

7. Memcached

Disk access is slow. Network access is slow. Databases typically use both.

Memory is fast. Using a local cache avoids the overhead of network and disk access. Combine these truths and you get memcached, a “distributed memory object caching system” originally developed for the Perl-based blogging platform LiveJournal.

If your application isn’t distributed across multiple servers, you probably don’t need memcached. Simpler caching approaches — serializing data and storing it in a temporary file, for example — can eliminate a lot of redundant work on each request. In fact, this is the sort of low-hanging fruit we consider when helping our clients tune their apps.

One of the easiest and most universal ways to cache data in memory is to use the shared memory helpers in , a caching system originally developed by our colleague George Schlossnagle. Consider the following example:

  1.   
  2. $feed = apc_fetch('news');   
  3.   
  4. if ($feed === FALSE) {   
  5.     $feed = file_get_contents('');   
  6.     // Store this data in shared memory for five minutes.   
  7.     apc_store('news'$feed, 300);   
  8. }   
  9.   
  10. // Do something with $feed.   
  11.   
  12. ?>  

With this type of caching, you don’t have to wait on a remote server to send the feed data for every request. Some latency is incurred — up to five minutes in this example — but this can be adjusted to as close to real time as your app requires.

8. Use a Framework

All decisions have consequences. We appreciate frameworks — in fact, the main developers behind and work with us at OmniTI — but using one doesn’t magically make what you’re doing better.

In December, our colleague Paul Jones wrote an article for PHP Advent called , in which he compares frameworks to business franchises. He refers to a suggestion by Michael Gerber from his book “The E-Myth Revisited”:

Gerber notes that to run a successful business, the entrepreneur needs to act as if he is going to sell his business as a franchise prototype. It is the only way the business owner can make the business operate without him being personally involved in every decision.

This is good advice. Whether you’re using a framework or defining your own standards and conventions, it’s important to consider the value from the perspective of future developers.

Although we would love to give you a universal truth, extending this idea to suggest that a framework is always appropriate isn’t something we’re willing to do. If you ask us whether you should use a framework, the best answer we could give is, “It depends.”

9. Use the Suppression Operator Correctly

Always try to avoid using the error suppression operator. In the previous article, the author states:

The @ operator is rather slow and can be costly if you need to write code with performance in mind.

Error suppression is slow. This is because PHP dynamically changes error_reporting to 0 before executing the suppressed statement, then immediately changes it back. This is expensive.

Worse, using the error suppression operator makes it difficult to track down the root cause of a problem.

The previous article uses the following example to support the practice of assigning a variable by reference when it is unknown if $albus is set:

  1.   
  2. $albert =& $albus;   
  3.   
  4. ?>  

Although this works — for now — relying on strange, undocumented behavior without a very good understanding of why it works is a good way to introduce bugs. Because $albert is assigned to $albus by reference, future modifications to $albus will also modify $albert.

A much better solution is to use isset(), with braces:

  1.   
  2. if (!isset($albus)) {   
  3.     $albert = NULL;   
  4. }   
  5.   
  6. ?>  

Assigning $albert to NULL is the same as assigning it to a nonexistent reference, but being explicit greatly improves the clarity of the code and avoids the referential relationship between the two variables.

If you inherit code that uses the error suppression operator excessively, we’ve got a bonus tip for you. There is a new that disables error suppression.

10. Use isset() Instead of strlen()

This is actually a neat trick, although the previous article completely fails to explain it. Here is the missing example:

  1.   
  2. if (isset($username[5])) {   
  3.     // The username is at least six characters long.   
  4. }   
  5.   
  6. ?>  

When you treat strings as arrays, each character in the string is an element in the array. By determining whether a particular element exists, you can determine whether the string is at least that many characters long. (Note that the first character is element 0, so $username[5] is the sixth character in $username.)

The reason this is slightly faster than strlen() is complicated. The simple explanation is that strlen() is a function, and isset() is a language construct. Generally speaking, calling a function is more expensive than using a language construct.

阅读(474) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~