Skip to content

Instantly share code, notes, and snippets.

@ghedipunk
Created May 30, 2015 14:45
Show Gist options
  • Save ghedipunk/aa525740436120a6ad47 to your computer and use it in GitHub Desktop.
Save ghedipunk/aa525740436120a6ad47 to your computer and use it in GitHub Desktop.
<?php
/**
* submit.php
*
* NOTE: THIS IS PART OF AN EXAMPLE OF VERY INSECURE CODE! DO NOT USE THIS!
*/
if (empty($_POST['formid']))
{
// Display some nasty message here, every form on the site should have a formid field.
exit();
}
$isValid = true;
// Every form should have a CSRF token, so check if it's valid here.
// In our case, a CSRF token becomes invalid after an hour, to minimize the risk of
// attackers finding a currently useful one and letting it sit around in their server
// for extended periods of time. We present the contents of the form to them again
// in case they aren't the victims of a CSRF attack, but rather are simply writing a novel
// in the comments section.
// NOTE: THIS IS A SANE CSRF POLICY (as of current best practices) THAT TAKES USER EXPERIENCE INTO ACCOUNT.
if (!validateCsrfToken($_POST['csrf-token']))
{
$_SESSION['formstate'][$_POST['formid']]['validationMessages'][] = 'It looks like you have been idle for too long. Please try submitting the form again.';
$isValid = false;
}
switch ($_POST['formid'])
{
case 'comment-form':
$_SESSION['formstate'][$_POST['formid']]['comment'] = $_POST['comment'];
$_SESSION['formstate'][$_POST['formid']]['current-article'] = $_POST['current-article'];
if (!validate($_POST['comment'], 'basichtml')); // assuming validate($contentToValidate, $rulesToValidateWith). Please assum that the rule 'basichtml' would be triggered on unsafe HTML tags like <script>.
{
$_SESSION['formstate'][$_POST['formid']]['validationMessages'][] = 'There was a problem with the comment as submitted.';
$isValid = false;
}
break;
// ... etc.
}
if ($isValid)
{
// Passed validation, so post this comment. (Or whatever the form is... ;-) )
processForm($_POST['form_id'], $_SESSION['formstate'][$_POST['formid']);
}
else
{
// Failed validation, go back to the article and have the user fix it.
$articlePath = getArticlePath($_POST['current-article']);
header('Location: ' . $articlePath, true, 303);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment