O'Reilly logo

Essential PHP Security by Chris Shiflett

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Cross-Site Request Forgeries

A cross-site request forgery (CSRF) is a type of attack that allows an attacker to send arbitrary HTTP requests from a victim. The victim is an unknowing accomplice—the forged requests are sent by the victim, not the attacker. Thus, it is very difficult to determine when a request represents a CSRF attack. In fact, if you have not taken specific steps to mitigate the risk of CSRF attacks, your applications are most likely vulnerable.

Consider a sample application that allows users to buy items—either pens or pencils. The interface includes the following form:

    <form action="buy.php" method="POST">
    <p>
    Item:
    <select name="item">
      <option name="pen">pen</option>
      <option name="pencil">pencil</option>
    </select><br />
    Quantity: <input type="text" name="quantity" /><br />
    <input type="submit" value="Buy" />
    </p>
    </form>

An attacker can use your application as intended to do some basic profiling. For example, an attacker can visit this form to discover that the form elements are item and quantity. The attacker also learns that the expected values of item are pen and pencil.

The buy.php script processes this information:

    <?php

    session_start();
    $clean = array();

    if (isset($_REQUEST['item'] && isset($_REQUEST['quantity']))
    {
      /* Filter Input ($_REQUEST['item'], $_REQUEST['quantity']) */

      if (buy_item($clean['item'], $clean['quantity']))
      {
        echo '<p>Thanks for your purchase.</p>';
      }
      else
      {
        echo '<p>There was a problem with your order.</p>';
      }
    }

    ?>

An attacker can first ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required