Skip to content Skip to navigation

Top 6 security attacks in PHP

August 09, 2012
Top 6 security attacks in PHP

Be aware of the most common security threats to PHP applications is the important step to secure your PHP scripts may not be immune.  Here, the article is going to go over top 6 common security threads in PHP scripts. You may familiar with this, if not, this is a good time for you to read and keep in mind.

1. SQL injection

SQL injection is a kind of attack that malicious users enter SQL in form fields in a way that affects the execution of SQL statements. A variation is command injection, where user data is passed through system() or exec(). It shares the same mechanism as SQL injection but for shell commands.

1     $ username = $_POST['username'];

2     $query = "select * from auth where username = '".$username."'";

3     echo $query;

4     $db = new mysqli('localhost', 'demo', ‘demo', ‘demodemo');

5     $result = $db->query($query);

6     if ($result && $result->num_rows) {

7         echo "<br />Logged in successfully";

8     } else {

9         echo "<br />Login failed";

10   }


The above code, there is not proper filtered/escaped on user input value ($_POST['username']) on Line 1. This query could fail or even damage the DB if $username has a wrong format or contains substrings that transform your SQL statement to something else.

Preventing SQL injection


  • Filter data using mysql[i]_real_escape_string()
  • Manually check each piece of data is of the right type
  • Use prepared statements and bind variables

Use prepared prepared statements

  • Separating data and SQL logic
  • The prepared statements will do filtering (e.g., escape) automatically
  • Use it as a coding standard, can help limit problems caused by new developers within your organization.
1    $query = 'select name, district from city where countrycode=?';

2    if ($stmt = $db->prepare($query) )

3   {

4         $countrycode = 'hk';

5         $stmt->bind_param("s", $countrycode);  

6         $stmt->execute();

7         $stmt->bind_result($name, $district);

8         while ( $stmt ($stmt->fetch() ){

9            echo $name.', '.$district;

10          echo '<br />';

11        }

12        $stmt->close();

13   }


2. XSS

XSS (Cross Site Scripting) is an attack by a user where they enter some data to your website that includes a client side script (generally JavaScript). If you output this data to another web page without filtering it, this script will be executed.

Accept text comments from user

1    <?php

2      if (file_exists('comments')) {

3          $comments = get_saved_contents_from_file('comments');

4       } else {

5          $comments = '';

6       }


8       if (isset($_POST['comment'])) {

9           $comments .= '<br />' . $_POST['comment'];

10         save_contents_to_file('comments', $comments);

11     }

12     ?>


Outputting comments to (another) user:

1     <form action='xss.php' method='POST'>

2         Enter your comments here: <br />

3         <textarea name='comment'></textarea> <br />

4         <input type='submit' value='Post comment' />

5         </form><hr /><br />


7       <?php echo $comments; ?>


What's going to happen??

  • Annoying popups
  • Refresh or redirections
  • Corrupted pages or forms
  • Steal cookies
  • AJAX ( XMLHttpRequest )
Preventing XSS

In order to prevent XSS attact, proper filter output to the browser through htmlentities() in PHP. Basic usage of htmlentities() is simple, but there are many advanced controls. See the XSS cheat sheet at here


3. Session fixation

Session security works on the assumption that a PHPSESSID is hard to guess. However, PHP can either accept a session id through a cookie or through the URL. Tricks a victim to use a specific (or another) session

ID or a phishing attack is possible.

Session fixation - A typical session fixation attack


4. Session capturing and hijacking

It's the same idea of Session fixation, however, it involves stealing the session ID. If session IDs are stored in cookies, attackers can steal them through XSS and JavaScript. Session IDs can also be sniffed or obtained from proxy servers if contained in the URL.

Preventing Session capturing and hijacking

  • Regenerate IDs
  • If using sessions, always user SSL

5. Cross Site Request Forgeries (CSRF)

CSRF refers to a request for a page that looks like it was initated by a site's trusted users, but wasn't deliberately. Many variations. One of the example:

Preventing Cross Site Request Forgeries

In general make sure the users come from your forms, and each form submission is matched to an individual form that you send out. There are two guides have to remember:

  • User session with appropiate security measures, e.g.: Regenerate IDs and user SSL for every session.
  • Generate another one-time token and embed it in the form, save it in the session (one of the session variable), and check it on submission.

6. Code injection

Code injection is the exploitation of a computer bug that is caused by processing invalid data. The problem occurs when you accidentally execute arbitrary code, typically through file inclusion. Poorly written code can allow a remote file to be included and executed. Many PHP functions such as require can take an URL or a filename. Example:

1  <form>Choose theme:

2  <select name = theme>

3  <option value = blue>Blue</option>

4  <option value = green>Green</option>

5  <option value = red>Red</option>

6  </select>

7  <input type = submit>

8   </form>

9   <?php

10   if($theme) {

11     require($theme.'.txt');

12    }

13 ?>


The example on above, Passing user input as a filename or part of a filename invites users to start filenames with "http://".

Prevent Code Injection

  • Filter user input
  • Disable allow_url_fopen and/or allow_url_include setting in php.ini.  This disables require/include/fopen of remote files.

Other general principles
  • Don’t rely on server configuration to protect you especially if your web server/PHP is managed by your ISP, or if your web site might bebe migrated/deployed somewhere else in future migrated/deployed somewhere else in future. Embed the security-aware checking/logic in the website code (PHP, HTML, JavaScript, etc.)
  • Design your server-side scripts with security from the ground up: e.g., use a single line of execution that begins with a single point of authentication and data cleaning

    - E.g., delegate all login/security checking logic in one PHP function/file to be included in all security-sensitive pages

    - Problems can be easily checked and solved
  • Keep your code up to date.  Stay on top of patches and advisories

Cover image borrow from