Skip to content

Instantly share code, notes, and snippets.

@0xMatt
Last active August 29, 2015 14:15
Show Gist options
  • Save 0xMatt/05dfc21fd21013c93d4e to your computer and use it in GitHub Desktop.
Save 0xMatt/05dfc21fd21013c93d4e to your computer and use it in GitHub Desktop.
A basic form. Susceptible to csrf and no post/redirect/get implementation.
<?php
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Set required fields
$required = [
'field_1',
'field_2'
];
// Filter post values
array_walk($_POST, function (&$item, $key) {
$item = htmlspecialchars(trim($item));
// $item = mysql_real_escape_string($item);
});
// Make sure we have required fields
foreach ($required as $require) {
if (array_key_exists($require, $_POST) && empty(trim($_POST[$require]))) {
$errors[] = $require . ' can not be empty';
}
}
// Other checks...
if (! count($errors)) {
// Make sure field_1 is email
if (! filter_var($_POST['field_1'], FILTER_VALIDATE_EMAIL)) {
$errors[] = 'field_1 is not a valid email address';
}
if (! count($errors)) {
// Form is valid, process data
}
}
}
?>
<form method="post">
<?php foreach($errors as $error): ?>
<p><?php echo $error; ?></p>
<?php endforeach; ?>
<input type="text" name="field_1" value="<?php echo (isset($_POST['field_1']) ? $_POST['field_1'] : '' ) ?>" />
<input type="text" name="field_2" value="<?php echo (isset($_POST['field_2']) ? $_POST['field_2'] : '' ) ?>" />
<input type="text" name="field_3" value="<?php echo (isset($_POST['field_3']) ? $_POST['field_3'] : '' ) ?>" />
<input type="text" name="field_4" value="<?php echo (isset($_POST['field_4']) ? $_POST['field_4'] : '' ) ?>" />
<button type="submit">Submit</button>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment