Basic Form Handling with POST
Handles a basic `POST` form by checking the request method, trimming fields, validating email, and returning errors or clean data.
Purpose
Handles a basic `POST` form by checking the request method, trimming fields, validating email, and returning errors or clean data.
Snippet details
ContextFormLevelProductionCopy-and-paste statusMarked safe after review.Categories
- Forms and Validation
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Basic Form Handling with POST.
*
* Purpose:
* Validates a small POST form without merging query data into POST handling, then returns either
* cleaned values or field-specific errors.
*
* @param string $request_method Usually `$_SERVER['REQUEST_METHOD']`.
* @param array $post_values Usually `$_POST`.
* @return array Form handling status, cleaned data, and errors.
*/
function ogSnippetBasicFormHandlingPost(string $request_method, array $post_values): array {
$errors = array();
$clean_data = array(
'pilot_name' => '',
'contact_email' => '',
'mission_note' => ''
);
if (strtoupper($request_method) !== 'POST') {
return array(
'ok' => false,
'submitted' => false,
'data' => $clean_data,
'errors' => $errors
);
}
if (isset($post_values['pilot_name']) === true) {
$clean_data['pilot_name'] = trim((string) $post_values['pilot_name']);
}
if (isset($post_values['contact_email']) === true) {
$clean_data['contact_email'] = trim((string) $post_values['contact_email']);
}
if (isset($post_values['mission_note']) === true) {
$clean_data['mission_note'] = trim((string) $post_values['mission_note']);
}
if ($clean_data['pilot_name'] === '') {
$errors['pilot_name'] = 'Pilot name is required.';
}
if ($clean_data['contact_email'] === '' || filter_var($clean_data['contact_email'], FILTER_VALIDATE_EMAIL) === false) {
$errors['contact_email'] = 'A valid contact email is required.';
}
if (strlen($clean_data['mission_note']) > 600) {
$errors['mission_note'] = 'Mission note must be 600 characters or fewer.';
}
return array(
'ok' => count($errors) === 0,
'submitted' => true,
'data' => $clean_data,
'errors' => $errors
);
}
$current_request_method = '';
if (isset($_SERVER['REQUEST_METHOD']) === true) {
$current_request_method = (string) $_SERVER['REQUEST_METHOD'];
}
$form_report = ogSnippetBasicFormHandlingPost($current_request_method, $_POST);
if ($form_report['submitted'] === true && $form_report['ok'] === true) {
echo 'Firefly dispatch request accepted for '.$form_report['data']['pilot_name'].'.';
}