Friday, 11 August 2017

How to use Shortcut of else

How to use Shortcut of else

This tip accidentally stumbles upon a helpful apply, that is to continually initialize variables before you utilize them. take into account a conditional statement that determines whether or not a user is Associate in Nursing administrator supported the username:

<?php

if (auth($username) == 'admin') {
    $admin = TRUE;
} else {
    $admin = FALSE;
}

?>

This appears safe enough, as a result of it’s straightforward to grasp at a look. Imagine a rather additional elaborate example that sets variables for name and email moreover, for convenience:

<?php

if (auth($username) == 'admin') {
    $name = 'Administrator';
    $email = 'admin@example.org';
    $admin = TRUE;
} else {
    /* Get the name and email from the database. */
    $query = $db->prepare('SELECT name, email
                           FROM   users
                           WHERE  username = :username');
    $query->execute(array('username' => $clean['username']));
    $result = $query->fetch(PDO::FETCH_ASSOC);
    $name = $result['name'];
    $email = $result['email']; 
    $admin = FALSE;
}


?>

Because $admin remains continually expressly set to either TRUE or FALSE, all is well, however if a developer later adds associate elseif, there’s a chance to forget:

<?php

if (auth($username) == 'admin') {
    $name = 'Administrator';
    $email = 'admin@example.org';
    $admin = TRUE;
} elseif (auth($username) == 'mod') {
    $name = 'Moderator';
    $email = 'mod@example.org';
    $moderator = TRUE;
} else {
    /* Get the name and email. */
    $query = $db->prepare('SELECT name, email
                           FROM   users
                           WHERE  username = :username');
    $query->execute(array('username' => $clean['username']));
    $result = $query->fetch(PDO::FETCH_ASSOC);
    $name = $result['name'];
    $email = $result['email']; 
    $admin = FALSE;
    $moderator = FALSE;
}

?>

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:

<?php

$admin = FALSE;
$moderator = FALSE;

if (auth($username) == 'admin') {
    $name = 'Administrator';
    $email = 'admin@example.org';
    $admin = TRUE;
} elseif (auth($username) == 'mod') {
    $name = 'Moderator';
    $email = 'mod@example.org';
    $moderator = TRUE;
} else {
    /* Get the name and email. */
    $query = $db->prepare('SELECT name, email
                           FROM   users
                           WHERE  username = :username');
    $query->execute(array('username' => $clean['username']));
    $result = $query->fetch(PDO::FETCH_ASSOC);
    $name = $result['name'];
    $email = $result['email'];
}

?>

Regardless of what the remainder of the code will, it’s currently clear that $admin is fake unless it's expressly set to one thing else, and also the same is true for $moderator. This conjointly hints at another smart security apply, that is to fail safely. The worst that may happen as a results of not modifying $admin or $moderator in associate degreey of the conditions is that somebody United Nations agency is an administrator or moderator isn't treated mutually.

If you wish to route one thing, associate degreed you’re feeling to a small degree thwarted that our example includes an else, we've a bonus tip which may interest you. We’re not sure it will be thought-about a route, however we have a tendency to hope it’s useful notwithstanding.

Consider a operate that determines whether or not a user is allowed to look at a selected page:

<?php
 
function authorized($username, $page) {
    if (!isBlacklisted($username)) {
        if (isAdmin($username)) {
            return TRUE;
        } elseif (isAllowed($username, $page)) {
            return TRUE;
        } else {
            return FALSE;
        }
    } else {
        return FALSE;
    }
}
 
?>

This example is really pretty easy, as a result of there area unit solely 3 rules to consider: directors area unit forever allowed access; people who area unit blacklisted area unit ne'er allowed access; and isAllowed() determines whether or not anyone else has access. (A special case exists once associate administrator is blacklisted, however that's associate unlikely chance, therefore we’re ignoring it here.) we have a tendency to use functions for the foundations to stay the code easy and to specialise in the logical structure.

There area unit varied ways in which this instance will be improved. If you wish to scale back the amount of lines, a compound conditional will help:

<?php
 
function authorized($username, $page) {
    if (!isBlacklisted($username)) {
        if (isAdmin($username) || isAllowed($username, $page)) {
            return TRUE;
        } else {
            return FALSE;
        }
    } else {
        return FALSE;
    }
}
 
?>

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

<?php
 
function authorized($username, $page) {
    if (!isBlacklisted($username) && (isAdmin($username) || isAllowed($username, $page)) {
        return TRUE;
    } else {
        return FALSE;
    }
}
 
?>

Finally, this can be reduced to a single return:

<?php
 
function authorized($username, $page) {
    return (!isBlacklisted($username) && (isAdmin($username) || isAllowed($username, $page));
}
 
?>

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:

<?php
 
function authorized($username, $page) {
 
    if (isBlacklisted($username)) {
        return FALSE;
    }
 
    if (isAdmin($username)) {
        return TRUE;
    }
 
    return isAllowed($username, $page);
}
 
?>

This uses a lot of lines of code, however it’s terribly straightforward and unimposing (we’re proudest of our code once it’s the smallest amount impressive). a lot of significantly, this approach reduces the quantity of context you want to continue with. for instance, as presently as you’ve determined whether or not the user is blacklisted, you'll be able to safely ignore it. this can be significantly useful once your logic is a lot of difficult.

Thursday, 10 August 2017

Know the Difference Between Comparison Operators

Know the Difference Between Comparison Operators

This is a decent tip, however it's missing a sensible example that demonstrates once a non-strict comparison will cause issues.

If you employ strpos() to see whether or not a substring exists at intervals a string (it returns FALSE if the substring isn't found), the results may be misleading:

<?php

$authors = 'Chris & Sean';

if (strpos($authors, 'Chris')) {
    echo 'Chris is an author.';
} else {
    echo 'Chris is not an author.';
}

?>

Because the substring Chris happens at the terribly starting of Chris &amp; Sean, strpos() properly returns zero, indicating the primary position within the string. as a result of the conditional statement treats this as a Boolean, it evaluates to FALSE, and also the condition fails. In alternative words, it's like Chris isn't associate degree author, but he is!


This can be corrected with a strict comparison:


<?php

if (strpos($authors, 'Chris') !== FALSE) {
    echo 'Chris is an author.';
} else {
    echo 'Chris is not an author.';
}


?>


Tuesday, 8 August 2017

How to Use an SQL Injection

How to Use an SQL Injection

This tip is just a link to a useful resource with no discussion on how to use it. Studying several permutations of a specific attack can be useful, but your time is spent better learning to protect against it. In addition, there is much more in Web application security than in SQL injection. XSS (Cross-Site Scripting) and CSRF (Cross-Site Request Forgeries), for example, are at least as common and at least as dangerous.We can provide a much needed context, but because we do not want to focus too much on an attack, we will first take a step back. Every developer should be familiar with good security practices, and applications should be designed with these practices in mind. A fundamental rule is to never trust the data you get from somewhere else. Another rule is to escape data before sending it to another location. Combined, these rules can be simplified to form a basic safety principle: filter inlet, exhaust outlet (FIEO).The root cause of SQL injection is a failure to exit the 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 applications that construct queries as follows:


<?php

$query = "SELECT *
          FROM   users
          WHERE  name = '{$_GET['name']}'";
         
?>


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:

<?php

// Initialize arrays for filtered and escaped data, respectively.
$clean = array();
$sql = array();

// Filter the name. (For simplicity, we require alphabetic names.)
if (ctype_alpha($_GET['name'])) {
    $clean['name'] = $_GET['name'];
} else {
    // The name is invalid. Do something here.
}

// Escape the name.
$sql['name'] = mysql_real_escape_string($clean['name']);

// Construct the query.
$query = "SELECT *
          FROM   users
          WHERE  name = '{$sql['name']}'";

?>

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:

<?php

// Provide the query format.
$query = $db->prepare('SELECT *
                       FROM   users
                       WHERE  name = :name');

// Provide the query data and execute the query.
$query->execute(array('name' => $clean['name']));

?>

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

HTML APIs: What They Are And How To Design A Good One

As JavaScript developers, we regularly forget that not everybody has a similar data as USA. It’s referred to as the curse of knowledge:...