Loading...

Tips for Defensive Programming in PHP

View: 389    Dowload: 0   Comment: 0   Post by: hanhga   Category: Php&mySql   Fields: Other

Simply put, failing fast and loudly means that when an error occurs, it will do so as early as possible, and alert whomever it should alert, as opposed to silently continuing on in an error state that may cause more issues. Here is an excellent article on fail-fast style development. The premise of fail-fast methodology is to fail when acquiring input that might later compromise the program (or, more generally, to enter a failure state as soon as any problems could possibly be detected, rather than allowing bad data to travel and a program to run un-checked, or worse, bad data to be stored somewhere). This is most useful when dealing with user input, or dealing with input that is arriving from outside the script, module, or even out of your system via an API. An example of where this could be employed would be a check for invalid values or data types passed into functions.

function thisTestFunction($testInt)
{
 if(!is_int($testInt)){
 // Do something here
 }
}

One mistake that some programmers make with fail-fast methodology is to simply throw Exceptions and errors out to the user without making proper provisions for handling them. You don’t want normal users to be worried or confused by your error messaging. And more importantly, you don’t want users with malicious intent learning things from the information displayed to them. Display a helpful message to the user, log your errors, and perform any other tasks that need to be a result of that exception. You don’t want to just fail fast, you also want to be loud (know there’s a problem, right away) and secure (don’t let your poor exception handling or complete lack thereof cause even more security issues).

Input Validation

There are many methods by which to validate user input safely.

Typecasting is an interesting way to “validate” user input. Sometimes it goes a bit like this:

$member->property = (int) $_GET['property'];

Instead of using another method to avoid cross-site scripting attacks, the value is simply being captured, typecast, and assigned. This only works when you have an expected type, and any value of that type is safe (Otherwise, you’d need to also check for appropriate int values). The problem with this approach, that I see (in most situations) is that you aren’t really checking the input, you’re just forcing it to become what it should be. This could have unforeseen consequences. Instead, a better approach might be to check for appropriate values using filter_input()Here is a great article on that subject. Basically, that comes out like this:

$member->property = filter_input(INPUT_GET, 'property', FILTER_VALIDATE_INT);

if (false === $member->property) {
  throw new Exception('Property was not an int');
}

There are many benefits to using the native filter_input function in modern PHP, and you can read more about them in the aforementioned article or on php.net.

Preventing Accidental Assignment in Comparisons

This is an easy, and often noted, tenet of defensive programming. A simple change in the way that you do your comparisons can have great effects. Consider the following:

if($member->property == 12345){
 // Do crazy cool stuff
} else {
 // Don't do any fun stuff
}

This is a relatively normal comparison, yes? However, what happens if you accidentally use the “=” instead of “==” (or, in most cases, the even better “===”)? A simple slip of the finger on the keyboard? Absentmindedness, maybe? All of a sudden, your comparison now reads true, all of the time, in all cases. Unless you have a good IDE warning you about this, how long will it take you to find out? In some cases, this could be a silent error for some time. However, there’s an extremely simple way to prevent this:

if(12345 == $member->property){
 // Do crazy cool stuff
} else {
 // Don't do any fun stuff
}

Now, if you accidentally use one equals sign, the error will not be silent. Obviously, this may not occur often, it may be mitigated by your testing, and it’s not useful in all cases, especially when doing variable to variable comparisons. But it’s still not a bad idea if this tends to happen to you.

Dealing with Try/Catch and Exceptions

try/catch statements are another hot topic among PHP developers. Let’s first get a quick look at what we’re talking about.

try {
 if($member->property <= 0){
 throw new Exception("Value must be 1 or greater");
 }
 // If no exception was thrown, this will be output.
 echo "The value is acceptable";
} catch(Exception $e) {
 echo 'Message: '.$e->getMessage();
}

A well known tool of defensive programming is the try/catch statement and the Exception class. These are excellent for catching and logging errors, when used correctly. A good programmer will employtry/catch statements to anticipate possible errors or other situations that might disrupt the normal flow. When those Exceptions occur, they must be handled in an appropriate way. The user of the application, where required, should get a reasonable error message that is as useful as it can be without divulging sensitive information. The administrator(s) of the application should receive detailed alerts and/or logs. Exceptions that are mishandled, or ignored, ignore the “Fail Loudly” advice, and may allow the program to continue in essentially a silent error state for some time, which is not good for anyone involved.

Transactions

Transactions are a feature of databases that allow queries to be grouped together, so that if one query fails, all of them fail. This is an implementation of ACID, about which you can read more here. The idea is that grouping multiple queries together into one process can sometimes be a safer and more stable solution, especially when the queries depend on each other. PHP developers often completely ignore transactions, or assume that they are unnecessary, but when interacting with databases, a little bit of defensive programming can go a long way. Transactions are discussed in more depth in this excellent post, but in a nutshell, transactions allow you to run your MySQL updates, and then check the results before actually committing the results. If you are using PDO (you should be), you may use PDO methods to begin a transaction, commit the results, as well as roll back. In addition to the aforementioned overview of transactions, delve into them further with this in-depth guide.

Here’s a quick example of what the use of transactions in PDO might look like:

try{
 // Start the transaction
 $db->beginTransaction();

 // Perform one update
 $statement1 = $db->prepare("QUERY LANGAUGE HERE");
 $statement1->execute(array($a,$b));

 // Perform another update
 $statement2 = $db->prepare("MORE QUERY LANGUAGE HERE");
 $statement2->execute(array($a,$b,$c));

 // Commit the transaction
 $db->commit();
} catch(PDOException $ex) {
 // If an exception occurs, first, roll back updates
 $db->rollBack();
 // Then, in this block, further handle the exception
}

Tips for Defensive Programming in PHP

Simply put, failing fast and loudly means that when an error occurs, it will do so as early as possible, and alert whomever it should alert, as opposed to silently continuing on in an error state that may cause more issues

Posted on 23-02-2016 

Comment:

To comment you must be logged in members.

Files with category

  • Twitter-like Hashtag Function in PHP

    Twitter-like Hashtag Function in PHP

    View: 215    Download: 1   Comment: 0

    Category: Php&mySql     Fields: none

    If you ever want a function to hashtag and style words within a string which has '#' next to it like twitter. This piece of code will help

  • PSITS Automated Voting System

    PSITS Automated Voting System

    View: 233    Download: 12   Comment: 0

    Category: Php&mySql     Fields: none

    A free sourcecode for PSITS Automated Voting System develop in PHP programming language. The purposed of the system is to automate the process of voting and maintain the quality of data

  • PHP-University Application System

    PHP-University Application System

    View: 206    Download: 13   Comment: 0

    Category: Php&mySql     Fields: none

    Greeting from Malawi the warm heart of Africa. I developed this university registration system project just to share with the people who can make use of the project like this and at the same time for others like students who can learn from it. This...

  • School Event Management System in PHP/MSQLi

    School Event Management System in PHP/MSQLi

    View: 392    Download: 0   Comment: 2

    Category: Php&mySql     Fields: none

    This School Event Management System can create school events such as Volleyball games, Basketball, Cultural presentation, Election of school officers etc . During school election Instead of having a compile list of candidates and voters this system...

  • Resort Reservation System with PayPal/Credit Card/Debit Card Payment

    Resort Reservation System with PayPal/Credit Card/Debit Card Payment

    View: 186    Download: 0   Comment: 0

    Category: Php&mySql     Fields: none

    This reservation system has the ability to help its customers find available rooms, cottages and even function hall for their convenience . And in here, they will also have the idea of the room rates where they can quickly reserve for their family...

  • Activity log

    Activity log

    View: 190    Download: 0   Comment: 0

    Category: Php&mySql     Fields: none

    Simple program to track user's activity log-in time and online/offline status.

  • Electricks - eCommerce

    Electricks - eCommerce

    View: 178    Download: 0   Comment: 0

    Category: Php&mySql     Fields: none

    Electricks is an e-commerce website built using PHP, Bootstrap and some jQuery plugins. It has all the major functionalities of a typical e-shop. This project was used to present in Southern Luzon State University - Lucban. Feel free to use this code...

  • Simple Email App Using PHP

    Simple Email App Using PHP

    View: 156    Download: 1   Comment: 0

    Category: Php&mySql     Fields: none

    Creating a simple PHP script using mail function for sending out emails.

 
File suggestion for you
Loading...
File top downloads
Loading...
Loading...
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd