Join the forums now, and start posting to receive access to our Scripts Vault!
<form action="action.php" method="post">Value 1<input type="text" name="value1">Value 2<input type="text" name="value2"><input type="submit" value="Submit"></form>
CSRF stands for "Cross-Site Request Forgery", and CSRF attacks are similar in scope and methodology to XSS attacks. CSRF attacks usually either exploit the fact that many websites perform actions on HTTP GET requests—deleting blog posts, buying items etc.—or spoof a client request to a resource so that the website believes the request is genuine. Either way, the victim performs an action on a website that trusts him—usually his own—that he did not intend to happen.
The first is rather simple: never, ever use GET for any critical task. Instead, use a POST form. Such requests are harder to forge and have the added bonus that they are impossible to load into HTML image/script tags, eliminating an attacker's ability to exploit your site remotely.The second is to make sure all requests originate from your own forms, eliminating the possibility that the request could have been loaded from a fake form on a different webpage. To do this, we can create a value— known by some as a "nonce", but here referred to as a "token"—that is created especially for the form, submitted along with it, and checked— along with the usual permission checks—before the action is performed.Here's an example that creates and checks a token before deleting a forum post:Code: [Select]<?phpsession_start();if( !empty($_POST['post_id'] ) { if( !user->is_a_moderator ) die; if( empty($_POST['token']) || $_POST['token'] != $_SESSION['token'] ) die; // All fine: delete the post. delete_post( intval($_POST['post_id']) ); // Unset the token, so that it cannot be used again. unset($_SESSION['token']);}$token = md5(uniqid(rand(), true));$_SESSION['token'] = $token;?><form method="post"><p>Post ID to delete:</p><p><input type="text" name="post_id" /></p><input type="hidden" name="token" value="<?php echo $token; ?>" /></form>As we can see, using a POST form with a generated token is simple, straightforward and eliminates the possibility of CSRF attacks.
<?phpsession_start();if( !empty($_POST['post_id'] ) { if( !user->is_a_moderator ) die; if( empty($_POST['token']) || $_POST['token'] != $_SESSION['token'] ) die; // All fine: delete the post. delete_post( intval($_POST['post_id']) ); // Unset the token, so that it cannot be used again. unset($_SESSION['token']);}$token = md5(uniqid(rand(), true));$_SESSION['token'] = $token;?><form method="post"><p>Post ID to delete:</p><p><input type="text" name="post_id" /></p><input type="hidden" name="token" value="<?php echo $token; ?>" /></form>
Because GET URLs should be idempotent and cacheable. POST is for making changes.