Forms, Validation & Input Handling Passs
Harden an existing PHP website’s forms and request handling against invalid input, duplicate submissions, CSRF, malformed data, inconsistent validation, unsafe defaults, weak error states, and client/server disagreement.
You are the lead form, validation, request-handling, and input-integrity engineer.
Perform a comprehensive pass on the existing website’s forms, submitted data, server-side validation, client-side feedback, and mutation workflows.
The project is typically built with:
- PHP;
- MySQL;
- HTML;
- CSS;
- browser-native JavaScript;
- existing project utilities.
Do not introduce frameworks or unnecessary third-party libraries.
Primary question:
Where can malformed, missing, duplicated, stale, contradictory, or manipulated input cause incorrect data, confusing behavior, broken workflows, or security problems?
Then fix those problems.
Use:
trace input → define valid state → attack assumptions → implement → validate → search siblings
This is an implementation task, not merely an audit.
Scope
Inspect only systems that exist:
- HTML forms;
- GET/POST requests;
- JSON/AJAX requests;
- search/filter inputs;
- registration/account forms;
- settings;
- admin forms;
- file inputs;
- pagination;
- bulk actions;
- destructive actions;
- create/update/delete workflows;
- validation;
- normalization;
- CSRF;
- duplicate submission;
- error/success feedback.
Do not redesign the product, introduce a form framework, or perform unrelated UI/backend cleanup.
Core Rule
Client-side validation is UX.
Server-side validation is authority.
Never rely on:
required;- input types;
- min/max attributes;
- JavaScript;
- disabled controls;
- hidden fields;
- browser-generated requests;
as the only protection.
Assume requests can be constructed manually.
Priority
P0: input causes corruption, privilege changes, unauthorized mutation, data loss, or severe security issues.
P1: duplicate submissions, missing server validation, broken CSRF, unsafe field trust, impossible records.
P2: inconsistent validation, poor error handling, stale forms, weak normalization, confusing failure states.
P3: wording, minor feedback, small usability polish.
Fix P0/P1 first.
Map Each Form
For every meaningful form determine:
- who can submit it;
- what fields the user may control;
- what fields the server must derive;
- required validation;
- authorization;
- CSRF requirements;
- mutation performed;
- success behavior;
- failure behavior;
- duplicate/retry behavior.
Trace:
input → parse → validate → authorize → mutate → persist → respond
Do not skip layers because the UI normally prevents invalid actions.
Input Shape
Validate whether each value is actually the expected type.
PHP request values may unexpectedly be:
- missing;
- empty;
- arrays;
- malformed strings;
- extreme numbers.
Do not assume:
$_POST['name']
is always a string.
Check shape before operations such as:
trim;- comparisons;
- casting;
- database binding;
- string functions.
Required vs Optional
Make required/optional semantics explicit.
Distinguish:
- missing;
- empty string;
- null;
- zero;
- false.
Do not use broad truthiness checks where 0 or "0" may be valid.
Numeric Validation
For IDs, quantities, prices, limits, and similar values:
- validate numeric format;
- enforce valid range;
- reject unexpected negatives;
- enforce sensible maximums;
- avoid silent coercion.
Do not treat:
(int) "garbage"
becoming 0 as successful validation.
Reject malformed input.
Strings
Validate where appropriate:
- length;
- trimming;
- allowed format;
- encoding;
- domain-specific rules.
Do not strip arbitrary punctuation merely because it looks unusual.
Preserve legitimate names, international text, and user content.
Validation should enforce product rules, not destroy valid input.
Enum / Choice Fields
For fields such as:
- status;
- role;
- category;
- sort;
- visibility;
- plan;
validate against an explicit allowed set.
Do not assume the submitted value came from your <select>.
Server-Owned Fields
Do not trust submitted values for data the server can determine itself.
Examples:
- current user ID;
- owner ID;
- role;
- admin status;
- price;
- discount eligibility;
- verified status;
- subscription state;
- created timestamp.
Derive authoritative values server-side.
Mass Assignment
Avoid generic logic that writes every submitted field into matching columns.
Use explicit allowed-field lists.
A browser can submit fields that the UI never displays.
Normalization
Normalize only where product semantics justify it.
Examples may include:
- trimming surrounding whitespace;
- canonical email handling;
- normalized identifiers.
Do not silently transform meaningful user input.
Apply normalization consistently between:
- validation;
- uniqueness checks;
- persistence;
- login/search where relevant.
CSRF
Protect consequential browser-authenticated mutations where appropriate.
Examples:
- profile changes;
- password/email changes;
- deletion;
- admin actions;
- purchases;
- settings;
- moderation.
Use a consistent server-validated token mechanism.
Reject missing or invalid tokens.
Do not rely solely on JavaScript, referrers, or cookie SameSite behavior.
Duplicate Submission
Test:
- double click;
- refresh after POST;
- browser retry;
- repeated AJAX request;
- two tabs;
- network timeout followed by retry.
Ask:
What happens if this form is submitted twice?
For consequential mutations, prevent unintended duplication using appropriate:
- idempotency;
- unique constraints;
- transactional checks;
- state validation.
Use POST/Redirect/GET where it improves normal browser behavior.
Stale Forms
Test editing data in multiple tabs.
Ask:
Can an older form overwrite newer changes?
For important records consider:
- version/revision values;
- updated timestamps;
- conditional updates;
- conflict detection.
Do not add concurrency controls everywhere without evidence.
Validation Ordering
A typical mutation should establish:
- request method;
- authentication;
- CSRF where applicable;
- input shape;
- field validity;
- authorization/ownership;
- current state/business rules;
- durable mutation.
Avoid expensive work before basic request validity is known.
Do not reveal sensitive existence information unnecessarily during validation.
Database Validation
Use MySQL constraints when they naturally express durable rules.
Examples:
- uniqueness;
- foreign-key integrity;
- required relationships.
Application validation improves feedback.
Database constraints protect against races and alternate code paths.
Use both where appropriate.
Error Handling
Validation failures should:
- explain what needs correction;
- preserve safe submitted values where appropriate;
- avoid raw PHP/SQL errors;
- avoid losing the entire form unnecessarily;
- clearly distinguish success from failure.
Do not claim success when persistence failed.
Field Errors
Prefer errors attached to the relevant field when practical.
Examples:
- invalid email;
- quantity out of range;
- required value missing.
Use a form-level message for cross-field or system failures.
Do not overwhelm users with implementation details.
Sensitive Fields
Do not repopulate sensitive values unnecessarily after failure.
Examples:
- passwords;
- authentication tokens;
- secrets.
Do not expose these values in HTML, logs, or query strings.
GET vs POST
Use GET for safe retrieval/filtering where appropriate.
Use state-changing requests for mutations rather than destructive GET links.
Do not perform actions such as delete simply because a URL was visited.
Search / Filter Forms
Validate:
- allowed filters;
- sort fields;
- page number;
- page size;
- date ranges.
Bound expensive values.
Do not allow arbitrary SQL fragments through sorting or filtering.
AJAX / JSON Forms
Treat fetch/AJAX endpoints exactly like normal endpoints.
Validate:
- authentication;
- authorization;
- CSRF where applicable;
- content type;
- JSON parsing;
- object shape;
- allowed fields.
Return consistent structured errors.
Do not assume JavaScript called the endpoint correctly.
File Inputs
Where forms upload files, validate:
- size;
- filename;
- type;
- storage;
- ownership;
- processing failures.
Do not trust browser-provided MIME type or filename.
Coordinate deeper file security with the site’s upload implementation.
Destructive Actions
For irreversible or high-impact actions:
- verify authorization;
- protect against CSRF;
- validate current state;
- use confirmation where appropriate;
- prevent accidental double execution.
Do not add confirmation dialogs to every trivial mutation.
Pattern Hunt
When one issue appears, inspect sibling forms.
Examples:
- one form trusts hidden owner ID → inspect other ownership forms;
- one AJAX route skips CSRF → inspect similar mutations;
- one field accepts arrays unexpectedly → inspect shared request helpers;
- one edit form can stale-overwrite → inspect similar editors.
Fix repeated patterns where justified.
Implementation Standard
For each meaningful issue:
- identify the input surface;
- define valid input/state;
- reproduce or prove the failure;
- identify root cause;
- implement the smallest robust fix;
- test valid submission;
- test malformed/missing input;
- test duplicate/retry behavior where relevant;
- test authorization/CSRF where relevant;
- inspect sibling forms.
Productive Loop
After each wave ask:
- Which form still trusts the browser too much?
- Which field lacks authoritative validation?
- What happens when a value is missing or an array?
- What happens on double submit?
- Can an old form overwrite newer data?
- Does failure preserve useful input?
- Does the server ever claim success before persistence succeeds?
- Which hidden field should be server-derived?
Continue while material, safely actionable issues remain.
Anti-Overengineering
Do not build:
- a form framework;
- giant validation DSLs;
- global sanitizers;
- complex request objects for trivial forms.
Prefer small reusable helpers only where patterns genuinely repeat.
Completion
Finish when:
- important forms validate server-side;
- privileged fields are server-derived;
- malformed input fails safely;
- consequential forms have appropriate CSRF protection;
- duplicate submissions are safe where important;
- stale-write problems discovered are addressed;
- errors are actionable;
- success is reported only after successful mutation;
- no discovered P0/P1 form issue remains without a blocker;
- legitimate workflows still function.
Final Report
Provide:
- Overall result
- Critical form/input fixes
- Validation improvements
- CSRF/request integrity
- Duplicate/stale submission handling
- AJAX/JSON forms
- Error/feedback improvements
- Exact validation performed
- Deliberately unchanged behavior
- Remaining risks with severity and next action
Final Directive
Treat every request as something the browser could construct manually.
Repeatedly ask:
Is this field actually the type we expect?
Who is allowed to control this value?
What happens if it is missing, duplicated, stale, extreme, or malformed?
What happens if the form is submitted twice?
Does the server independently validate everything that matters?
Leave behind the same website, but make its forms and request handling substantially more reliable, secure, predictable, and resistant to malformed input, duplicate submissions, stale state, and client manipulation.
View raw markdown
You are the **lead form, validation, request-handling, and input-integrity engineer**. Perform a comprehensive pass on the existing website’s forms, submitted data, server-side validation, client-side feedback, and mutation workflows. The project is typically built with: - PHP; - MySQL; - HTML; - CSS; - browser-native JavaScript; - existing project utilities. Do not introduce frameworks or unnecessary third-party libraries. Primary question: > **Where can malformed, missing, duplicated, stale, contradictory, or manipulated input cause incorrect data, confusing behavior, broken workflows, or security problems?** Then fix those problems. Use: > **trace input → define valid state → attack assumptions → implement → validate → search siblings** This is an implementation task, not merely an audit. ## Scope Inspect only systems that exist: - HTML forms; - GET/POST requests; - JSON/AJAX requests; - search/filter inputs; - registration/account forms; - settings; - admin forms; - file inputs; - pagination; - bulk actions; - destructive actions; - create/update/delete workflows; - validation; - normalization; - CSRF; - duplicate submission; - error/success feedback. Do not redesign the product, introduce a form framework, or perform unrelated UI/backend cleanup. ## Core Rule Client-side validation is UX. Server-side validation is authority. Never rely on: - `required`; - input types; - min/max attributes; - JavaScript; - disabled controls; - hidden fields; - browser-generated requests; as the only protection. Assume requests can be constructed manually. ## Priority **P0:** input causes corruption, privilege changes, unauthorized mutation, data loss, or severe security issues. **P1:** duplicate submissions, missing server validation, broken CSRF, unsafe field trust, impossible records. **P2:** inconsistent validation, poor error handling, stale forms, weak normalization, confusing failure states. **P3:** wording, minor feedback, small usability polish. Fix P0/P1 first. ## Map Each Form For every meaningful form determine: 1. who can submit it; 2. what fields the user may control; 3. what fields the server must derive; 4. required validation; 5. authorization; 6. CSRF requirements; 7. mutation performed; 8. success behavior; 9. failure behavior; 10. duplicate/retry behavior. Trace: > **input → parse → validate → authorize → mutate → persist → respond** Do not skip layers because the UI normally prevents invalid actions. ## Input Shape Validate whether each value is actually the expected type. PHP request values may unexpectedly be: - missing; - empty; - arrays; - malformed strings; - extreme numbers. Do not assume: > `$_POST['name']` is always a string. Check shape before operations such as: - `trim`; - comparisons; - casting; - database binding; - string functions. ## Required vs Optional Make required/optional semantics explicit. Distinguish: - missing; - empty string; - null; - zero; - false. Do not use broad truthiness checks where `0` or `"0"` may be valid. ## Numeric Validation For IDs, quantities, prices, limits, and similar values: - validate numeric format; - enforce valid range; - reject unexpected negatives; - enforce sensible maximums; - avoid silent coercion. Do not treat: > `(int) "garbage"` becoming `0` as successful validation. Reject malformed input. ## Strings Validate where appropriate: - length; - trimming; - allowed format; - encoding; - domain-specific rules. Do not strip arbitrary punctuation merely because it looks unusual. Preserve legitimate names, international text, and user content. Validation should enforce product rules, not destroy valid input. ## Enum / Choice Fields For fields such as: - status; - role; - category; - sort; - visibility; - plan; validate against an explicit allowed set. Do not assume the submitted value came from your `<select>`. ## Server-Owned Fields Do not trust submitted values for data the server can determine itself. Examples: - current user ID; - owner ID; - role; - admin status; - price; - discount eligibility; - verified status; - subscription state; - created timestamp. Derive authoritative values server-side. ## Mass Assignment Avoid generic logic that writes every submitted field into matching columns. Use explicit allowed-field lists. A browser can submit fields that the UI never displays. ## Normalization Normalize only where product semantics justify it. Examples may include: - trimming surrounding whitespace; - canonical email handling; - normalized identifiers. Do not silently transform meaningful user input. Apply normalization consistently between: - validation; - uniqueness checks; - persistence; - login/search where relevant. ## CSRF Protect consequential browser-authenticated mutations where appropriate. Examples: - profile changes; - password/email changes; - deletion; - admin actions; - purchases; - settings; - moderation. Use a consistent server-validated token mechanism. Reject missing or invalid tokens. Do not rely solely on JavaScript, referrers, or cookie SameSite behavior. ## Duplicate Submission Test: - double click; - refresh after POST; - browser retry; - repeated AJAX request; - two tabs; - network timeout followed by retry. Ask: > **What happens if this form is submitted twice?** For consequential mutations, prevent unintended duplication using appropriate: - idempotency; - unique constraints; - transactional checks; - state validation. Use POST/Redirect/GET where it improves normal browser behavior. ## Stale Forms Test editing data in multiple tabs. Ask: > **Can an older form overwrite newer changes?** For important records consider: - version/revision values; - updated timestamps; - conditional updates; - conflict detection. Do not add concurrency controls everywhere without evidence. ## Validation Ordering A typical mutation should establish: 1. request method; 2. authentication; 3. CSRF where applicable; 4. input shape; 5. field validity; 6. authorization/ownership; 7. current state/business rules; 8. durable mutation. Avoid expensive work before basic request validity is known. Do not reveal sensitive existence information unnecessarily during validation. ## Database Validation Use MySQL constraints when they naturally express durable rules. Examples: - uniqueness; - foreign-key integrity; - required relationships. Application validation improves feedback. Database constraints protect against races and alternate code paths. Use both where appropriate. ## Error Handling Validation failures should: - explain what needs correction; - preserve safe submitted values where appropriate; - avoid raw PHP/SQL errors; - avoid losing the entire form unnecessarily; - clearly distinguish success from failure. Do not claim success when persistence failed. ## Field Errors Prefer errors attached to the relevant field when practical. Examples: - invalid email; - quantity out of range; - required value missing. Use a form-level message for cross-field or system failures. Do not overwhelm users with implementation details. ## Sensitive Fields Do not repopulate sensitive values unnecessarily after failure. Examples: - passwords; - authentication tokens; - secrets. Do not expose these values in HTML, logs, or query strings. ## GET vs POST Use GET for safe retrieval/filtering where appropriate. Use state-changing requests for mutations rather than destructive GET links. Do not perform actions such as delete simply because a URL was visited. ## Search / Filter Forms Validate: - allowed filters; - sort fields; - page number; - page size; - date ranges. Bound expensive values. Do not allow arbitrary SQL fragments through sorting or filtering. ## AJAX / JSON Forms Treat fetch/AJAX endpoints exactly like normal endpoints. Validate: - authentication; - authorization; - CSRF where applicable; - content type; - JSON parsing; - object shape; - allowed fields. Return consistent structured errors. Do not assume JavaScript called the endpoint correctly. ## File Inputs Where forms upload files, validate: - size; - filename; - type; - storage; - ownership; - processing failures. Do not trust browser-provided MIME type or filename. Coordinate deeper file security with the site’s upload implementation. ## Destructive Actions For irreversible or high-impact actions: - verify authorization; - protect against CSRF; - validate current state; - use confirmation where appropriate; - prevent accidental double execution. Do not add confirmation dialogs to every trivial mutation. ## Pattern Hunt When one issue appears, inspect sibling forms. Examples: - one form trusts hidden owner ID → inspect other ownership forms; - one AJAX route skips CSRF → inspect similar mutations; - one field accepts arrays unexpectedly → inspect shared request helpers; - one edit form can stale-overwrite → inspect similar editors. Fix repeated patterns where justified. ## Implementation Standard For each meaningful issue: 1. identify the input surface; 2. define valid input/state; 3. reproduce or prove the failure; 4. identify root cause; 5. implement the smallest robust fix; 6. test valid submission; 7. test malformed/missing input; 8. test duplicate/retry behavior where relevant; 9. test authorization/CSRF where relevant; 10. inspect sibling forms. ## Productive Loop After each wave ask: - Which form still trusts the browser too much? - Which field lacks authoritative validation? - What happens when a value is missing or an array? - What happens on double submit? - Can an old form overwrite newer data? - Does failure preserve useful input? - Does the server ever claim success before persistence succeeds? - Which hidden field should be server-derived? Continue while material, safely actionable issues remain. ## Anti-Overengineering Do not build: - a form framework; - giant validation DSLs; - global sanitizers; - complex request objects for trivial forms. Prefer small reusable helpers only where patterns genuinely repeat. ## Completion Finish when: - important forms validate server-side; - privileged fields are server-derived; - malformed input fails safely; - consequential forms have appropriate CSRF protection; - duplicate submissions are safe where important; - stale-write problems discovered are addressed; - errors are actionable; - success is reported only after successful mutation; - no discovered P0/P1 form issue remains without a blocker; - legitimate workflows still function. ## Final Report Provide: 1. **Overall result** 2. **Critical form/input fixes** 3. **Validation improvements** 4. **CSRF/request integrity** 5. **Duplicate/stale submission handling** 6. **AJAX/JSON forms** 7. **Error/feedback improvements** 8. **Exact validation performed** 9. **Deliberately unchanged behavior** 10. **Remaining risks with severity and next action** # Final Directive Treat every request as something the browser could construct manually. Repeatedly ask: > **Is this field actually the type we expect?** > **Who is allowed to control this value?** > **What happens if it is missing, duplicated, stale, extreme, or malformed?** > **What happens if the form is submitted twice?** > **Does the server independently validate everything that matters?** Leave behind the **same website**, but make its forms and request handling substantially more reliable, secure, predictable, and resistant to malformed input, duplicate submissions, stale state, and client manipulation.