Thursday, May 3, 2012

Tips for Writing Safe, Secure PHP Code

http://olex.openlogic.com/wazi/2012/tips-for-writing-safe-secure-php-code


PHP has established itself as a cornerstone of web development, and powers popular platforms such as WordPress and Joomla. However, because today’s Internet is rife with hackers searching for weaknesses in web applications’ security, PHP programmers must code defensively and guard against potentially destructive errors.
Before embarking on a discussion on how to code with a security mindset, consider some of the common techniques hackers use to try and breach a website.
One of the most common forms of attack is SQL injection. Many websites rely on a database to store information for the site and for user authentication. An injection attack tries to modify SQL code that is sent to the database in order to manipulate the site or circumvent user authentication. It works through HTML forms, in which data is entered by users, or in this case by an attacker.
For example, a programmer might use the following PHP statement when trying to authenticate a user:
$auth = mysql_query("SELECT username, password  FROM users WHERE username = '" . $_POST['username'] . "' and password = '" . md5($_POST['password']) . "'");
The danger here is that the input entered by the user is directly used in the SQL statement without any validation or checking.
If an attacker were to enter, for example, ' OR 1=1 # for the username, the SQL statement would be transformed into:
SELECT username, password  FROM users WHERE username = '' OR 1=1 # and password = '286755fad04869ca523320acce0dc6a4';
Everything after the # is ignored, and 1=1 is always true, so the hacker would trick the code into thinking the user is authenticated.
Similar to SQL injection, cross-site scripting (XSS) attempts to inject JavaScript code into a web page and use that code to load more code from an unrelated site (hence the term cross-site). If he’s successful, the hacker can run his own code in the victim’s browser, which lets him launch more complex attacks and even infect the victim’s computer with malware.
A simple example of XSS might target users when they register for a site. At that time users can enter information into form fields, including their name, which is often displayed on the user’s profile page as simple HTML. Suppose a hacker tried to use the following code for a username:
By entering the
Replacing the call to alert() with code to download a complex JavaScript from another site (e.g.

2 comments:

  1. Good guidance..And i would like to refer my friends also who are looking up for this..
    Hire Magento Developer

    ReplyDelete
  2. Thanks for sharing this very nice information. This info is very helpful for every PHP programmer. I will share this info to my friends. Keep it up.

    ReplyDelete