PHP Training
15/07/2013
Security becomes the top priority (or activity) of many PHP developers. Its place and importance keeps growing in every single project, open source or commercial. Every conference provides a talk about security and you can read PHP security on the magazine cover pages. Security in PHP application is a large topic. This article explains one of the most important part of any security policy: the input or data filtering. General security topics like XSS, SQL injections and other dangerous attacks will not be discussed here, take a look at the end of this article for a small list of resources. Don’t trust external data Practically all applications (web, desktop, console) depend on external input to create output or to start an action. This input comes from a user or another application (web services clients, bots, scanner, etc.). The rule #1 of every developer (you all know it, but it does not hurt to write it down once more) should be: Filter All Foreign Data Input filtering is one of the cornerstones of any application security, independently of the language or environment. PHP provides a wide range of tools and functions to filter or validate data, but unlike other languages, it does not have any standard functions to filter data (like cgi for perl). The new Filter extension fills this gap. What’s foreign data? Anything from a form Anything from $_GET, $_POST, $_REQUEST Cookies ($_COOKIES) Web services data Files Some server variables (e.g. $_SERVER['SERVER_NAME']) Environment variables Database query results Filter supports get, post, cookies, server and environment variables as well as defined variables (server and env support may not work in all sapi, for filter 0.11.0 or php 5.2.0). Why Filter? To test, validate and filter user input or custom data can rapidly be annoying and repetitive task. It is easy to forget a test or write an incomplete regular expression. The Filter extension aims to make data filtering less painful as this simple example shows: Check two integer _GET input values:
6. Use Ternary Operators
Instead of using an if/else statement altogether, consider using a ternary operator. PHP Value gives an excellent example of what a ternary operator looks like.
//PHP COde Example usage for: Ternary Operator
$todo = (empty($_POST[’todo’])) ? ‘default’ : $_POST[’todo’];
// The above is identical to this if/else statement
if (empty($_POST[’todo’])) {
$action = ‘default’;
} else {
$action = $_POST[’todo’];
}
?>
The ternary operator frees up line space and makes your code less cluttered, making it easier to scan. Take care not to use more than one ternary operator in a single statement, as PHP doesn’t always know what to do in those situations.
Click here to claim your Sponsored Listing.
Category
Contact the school
Telephone
Website
Address
G4, Lake City Towers, Teen Hath Naka
Mumbai
400604