Download the PHP package scratchwizard1/form-generator without Composer

On this page you can find all versions of the php package scratchwizard1/form-generator. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package form-generator

FormGenerator

Strict-typed PHP library for building, validating and processing HTML forms โ€” cleanly, safely and without messy PHP/HTML mixing.

Stop echoing long HTML strings. Stop manually parsing $_POST. Start writing structured, readable form logic.


๐Ÿ“š Table of Contents


๐Ÿ“Œ Overview

Working with HTML forms in plain PHP often results in:

FormGenerator provides a structured and modern alternative for pure PHP projects.


โœจ Features


๐Ÿค” Why not just use Symfony Forms / Laravel Validation?


๐Ÿ“ฆ Installation & Requirements

Requirements

Installation

1. Create a folder for your new project and initialize Composer

2. Install the library

3. In the root of your project, create index.php and load the autoloader

The library is ready to use ๐ŸŽ‰

Dependencies

The following packages are installed automatically via Composer:

Development (optional)

If you want to contribute or run tests:

Install dev dependencies:


๐Ÿš€ Quick Example

Below is a minimal example showing how a basic form can be defined using FormGenerator.

Generated HTML

The above definition produces clean, structured HTML:

What happens automatically?

When using the form builder:

No manual CSRF handling or hidden input management is required.


๐Ÿงฑ Form Builder

Element Methods Overview

All element methods are chainable and allow attribute configuration after creation.

Method Parameters Description
text($name) string $name Creates <input type="text">
email($name) string $name Creates <input type="email">
password($name) string $name Creates <input type="password">
number($name) string $name Creates <input type="number">
tel($name) string $name Creates <input type="tel">
url($name) string $name Creates <input type="url">
search($name) string $name Creates <input type="search">
date($name) string $name Creates <input type="date">
datetime($name) string $name Creates <input type="datetime-local">
time($name) string $name Creates <input type="time">
month($name) string $name Creates <input type="month">
week($name) string $name Creates <input type="week">
range($name) string $name Creates <input type="range">
color($name) string $name Creates <input type="color">
checkbox($name) string $name Creates <input type="checkbox">
radio($name) string $name Creates <input type="radio">
file($name) string $name Creates <input type="file">
hidden($name) string $name Creates <input type="hidden">
textarea($name) string $name Creates <textarea>
select($name) string $name Creates <select>
button($name, $content) string $name, string $content Creates <button>
submit($value) string $value Creates <input type="submit">
reset($value) string $value Creates <input type="reset">
image($name, $src, $alt) string $name, string $src, string $alt Creates <input type="image">
label($text) string $text Creates <label>
legend($text) string $text Creates <legend>
fieldset() โ€” Opens <fieldset>
endFieldset() โ€” Closes <fieldset>
html($html) string $html Inserts raw HTML

Special Notes

Button

Image Input

Raw HTML


Supported Attributes

All elements share a unified attribute API. Each attribute has a corresponding method. All methods are chainable.

Attribute Methods Overview

Attribute Method Parameter Type Notes
id ->id($value) string Sets element ID
name ->name($value) string Overrides generated name
class ->class($value) string CSS classes
style ->style($value) string Inline styles
value ->value($value) string Input value
placeholder ->placeholder($value) string Placeholder text
title ->title($value) string Tooltip text
dir ->dir($value) string Text direction
onclick ->onclick($value) string JS handler
pattern ->pattern($value) string Regex validation
list ->list($value) string Datalist ID
form ->form($value) string External form reference
accept ->accept($value) string File types
src ->src($value) string Image source
alt ->alt($value) string Alternative text
wrap ->wrap($value) string Textarea wrapping
autocomplete ->autocomplete($value) string Default: "on"

Numeric / Length Attributes

Attribute Method Parameter Type
minlength ->minlength($value) int
maxlength ->maxlength($value) int
size ->size($value) int
min ->min($value) int|float|string
max ->max($value) int|float|string
step ->step($value) int|float|string (default: "any")
rows ->rows($value) int
cols ->cols($value) int
width ->width($value) int
height ->height($value) int

Boolean Attributes

These attributes do not require parameters.

Attribute Method
required ->required()
disabled ->disabled()
readonly ->readonly()
hidden ->hidden()
autofocus ->autofocus()
multiple ->multiple()
checked ->checked()
selected ->selected()

Important Notes

1๏ธโƒฃ Null Values

Although attributes are internally stored as nullable properties,
public API methods do not accept null as a valid value.

If a value is not provided, the attribute is simply not rendered.

2๏ธโƒฃ Attribute Compatibility

If an attribute does not apply to a specific element, it is automatically ignored.

Since min() applies only to numeric/date inputs, it will not be rendered.

3๏ธโƒฃ Clean HTML Guarantee

The form builder ensures:

This guarantees valid and clean HTML output.


Advanced: setAttributes()

The setAttributes() method is available on every element instance created by the builder.

This includes:

Any component added through a builder method supports setAttributes().

Usage

Priority Rules

setAttributes() has higher priority than fluent attribute methods.

If the same attribute is defined in both places:

The final rendered output will be:

โœ” Values defined in setAttributes() override values defined via fluent methods.

Key Rules

Examples of valid keys:

Value Handling Rules

Value Type Rendering Result
string Rendered as attribute="value"
int / float Rendered as attribute="number"
true Rendered as a boolean attribute (e.g. required)
'true' (string) Rendered as attribute="true"
false / null Attribute is not rendered
array (for class / style) Values are merged automatically
Boolean Example

Output: required

Output: required="true"

When to Use setAttributes()

Use setAttributes() when:

Clean HTML Guarantee

When using setAttributes():

setAttributes() always renders the attributes you specify in a valid HTML form.


๐Ÿ“ฅ Receiving & Validating Data

FormGenerator automatically extracts and validates submitted form data.

Note: getDataFrom() receives data directly from the form submission โ€” even fields that fail validation are included in the output. Rules array is optional โ€” if omitted, all submitted data is returned without any validation.


getDataFrom() with formId

When a formId is provided, only data from that specific form is processed. All other submitted data is ignored.


getDataFrom() without formId

When no formId is provided, the function automatically reads it from a hidden input (<input type="hidden" name="formID">), which FormGenerator adds to every form automatically.


getDataFrom() without rules

If you omit the rules array, the function simply collects and returns all submitted data without any validation.

Example Outputs

Valid Submission (->getData()):

Invalid Submission (->getError()):

Each error always has a unique id and code for consistent handling. Only one error is returned at a time.


Validation Rules (All Supported Rules)

Value column legend

  • โ€” = rule does NOT require a value
  • โœ” required = rule requires a value (rule:value)
  • optional = value is optional
  • special = special behavior (no value after colon)
Rule Aliases Value Description Example
Alpha a, al, alpha โ€” Letters only alpha;
AlphaNumber an, aln, alphan, alnum, alphanum, alphanumber โ€” Letters and numbers only alphaNumber;
Boolean b, bool, boolean โ€” Must be a boolean value boolean;
Color c, color โ€” Valid color value color;
Date d, date โ€” Valid date date;
DateTime dt, datetime โ€” Valid datetime dateTime;
Email e, mail, email โ€” Valid email address email;
Enum in, en, enum โœ” required Must be one of the allowed values enum:option1,option2;
Nenum nin, nen, nenum โœ” required Must NOT be one of the allowed values nenum:option1,option2;
Equal eq, equal โœ” required Must equal the given value equal:value;
Nequal neq, nequal โœ” required Must NOT equal the given value nequal:value;
Extension ex, exten, extension โœ” required File extension validation with group normalization (e.g. jpg also allows jpeg, jpe). Leading dots are ignored. Multiple extensions can be specified separated by comma (,). extension:jpg,png;
Mime mim, mime โœ” required MIME type validation mime:image/png;
File f, file โ€” File input validation file;
Format fo, for, form, format โœ” required Format validation format:int
Ip i, ip โ€” Valid IP address ip;
Json j, json โ€” Valid JSON json;
Length l, len, length โœ” required Exact length length:5;
Max ma, max โœ” required Maximum numeric/date/time value max:100;
Min mi, min โœ” required Minimum numeric/date/time value min:10;
MaxLength mal, malen, malength, maxl, maxlen, maxlength โœ” required Maximum string length maxLength:10;
MinLength mil, milen, milength, minl, minlen, minlength โœ” required Minimum string length minLength:5;
MaxWords maw, maword, mawords, maxw, maxword, maxwords โœ” required Maximum word count maxWords:5;
MinWords miw, miword, miwords, minw, minword, minwords โœ” required Minimum word count minWords:3;
Month m, month โ€” Valid month month;
Number n, num, number โ€” Numeric value number;
Null null special If value is empty, adds null null;
NotNull nnull, notnull special If value is empty, adds empty string "" notnull;
Ignore ignore โ€” Field is completely ignored (not added) ignore;
Password p, pas, pass, password โ€” Password validation password;
Regex re, reg, regex โœ” required Must match regular expression regex:/^[a-z0-9]+$/i;
Required r, req, required โ€” Field is required required;
Save sa, sav, save optional Saves the uploaded file to the specified directory. Path is relative to project root. Can be provided as value or via FG_UPLOAD_PATH in .env. Must be placed last in the rule chain. save:uploads/files;
Size si, size โœ” required File size validation (units B, KB, MB, GB, TB default unit is MB when only number is provided) size:5; (=> 5MB)
StringRule s, str, string โ€” String validation string;
Tel te, tel optional Valid phone number (optionally restricted to ISO 3166-1 alpha-2 country codes) tel; or tel:SK,CZ;
Time ti, time โ€” Valid time time;
Url u, url โ€” Valid URL url;
Week w, week โ€” Valid week week;

Special Behavior Rules


Save Rule Behavior

Example .env key:


Tel Rule Behavior

Example .env key:


Format Rule

The format rule is used to convert the final validated value into a specific type.

It does not validate structure โ€” it transforms the output value after validation.

Syntax

Example:

This means: convert value to float and round it to 2 decimal places.

Supported Format Types

Format Type Description
round Rounds numeric value. Optional precision (default is 0).
integer Converts value to integer.
float Converts value to float.
string Converts value to string.
datetime Converts value to DateTime object.
boolean Converts value to boolean.

Format Behavior Details

round โ€” Converts value to float. Rounds using optional precision parameter. Default precision is 0.

integer โ€” Converts value to integer. Throws an error if value exceeds integer limits.

float โ€” Converts value to float. Throws an error for invalid, infinite, or NaN values.

string โ€” Converts value to string. Arrays are converted to string representation (except file inputs).

datetime โ€” Converts value to a DateTime object.

Supported input formats:

boolean โ€” Converts value using PHP FILTER_VALIDATE_BOOLEAN.

Accepted values include: true, false, 1, 0, on, off, yes, no.

Important Rules


Extension Group Behavior

File extensions are normalized into groups so that common variants are automatically accepted. If you specify one extension from a group, all grouped variants are allowed.

Supported Extension Groups (Automatic Normalization)


Modifiers

Modifiers change how validation behaves or how the result is returned.

Modifier Aliases
array a, ar, array
any an, any
cut c, cut
domain d, domain
exist e, exist
hash h, hash
only o, only
strict st, strict
v6 v6

Tests and Supported Modifiers

Test Modifier Behavior
alpha o Returns only alphabetic characters (filters out everything else).
alphaNumber o Returns only alphanumeric characters.
email d Additionally checks whether the email domain exists (DNS check).
enum o Only allowed values may appear in the input.
enum a Input is treated as array and must contain all defined allowed values.
enum an Input is treated as array and must contain at least one allowed value.
extension st Disables extension group normalization. Only explicitly defined extensions are allowed (no automatic variants such as jpg โ†’ jpeg, jpe).
ip v6 Validates IPv6 format only.
json ar Validates JSON and ensures decoded value is an array.
length c Cuts value to defined length if it exceeds limit.
maxLength c Cuts value to maximum length if it exceeds limit.
minLength c Pads value (with spaces) until minimum length is reached.
nenum o None of the disallowed values may appear in the input.
nenum a Input is treated as array and must NOT contain any disallowed values.
nenum an Input is treated as array and none of the values may match the forbidden list.
number i Validates that value is an integer number (numeric integer format required).
number f Validates that value is a float number (decimal format allowed).
number o Returns only numeric characters from input (filters everything else). Result is returned as string.
number o,i Returns only numeric characters from input. Result remains a string (convertible to integer).
number o,f Returns only numeric characters (including decimal separator). Result remains a string (convertible to float).
password h Returns hashed password using password_hash().
url e Validates that the URL exists (HTTP check).

Modifier Explanation


โš™๏ธ Validation Configuration (__CONFIG__)

The special __CONFIG__ key configures sanitization applied to values in this validation context.

Key Aliases Description Values Default
strip_tags s, st, strip, striptags, strip_tags Enables or disables strip_tags sanitization (removes HTML tags) true, t / false, f true
htmlspecialchars h, html, htmlspecial, htmlspecialchars Enables or disables HTML special character escaping true, t / false, f true

Example Configurations


๐Ÿ”Ž Standalone Validation

Validation engine can be used independently from form builder. All validation rules and behaviors apply in the same way as described in ๐Ÿ“ฅ Receiving & Validating Data section.


๐Ÿ›ก File Validation

FormGenerator validates uploaded files and optionally saves them using the save rule.

It validates:

Optionally saves:


๐Ÿ” Google reCAPTCHA Enterprise

Integration with Google reCAPTCHA Enterprise is handled via the google/cloud-recaptcha-enterprise package.


Setup

  1. Create a project in Google Cloud Console
  2. Enable the reCAPTCHA Enterprise API
  3. Generate and download a service account credentials file (JSON)
  4. Place it in your project, e.g. /config/google-recaptcha.json
  5. Initialize the integration using one of the following approaches:

Option A โ€” via captchaInit():

Option B โ€” via .env file (no code required):

When all three variables are defined in .env, calling captchaInit() is not necessary.


Note: Unlike standard reCAPTCHA, Google reCAPTCHA Enterprise does not use a secret key. Instead, it authenticates via a service account credentials file.


Credentials Resolution Order

The library resolves the credentials file in the following order:

  1. The third parameter passed to captchaInit()
  2. The FG_GOOGLE_APPLICATION_CREDENTIALS environment variable defined in .env
  3. The default fallback path: /config/google-recaptcha.json

All paths are resolved relative to the project root directory.


Score Threshold

reCAPTCHA Enterprise returns a risk score between 0.0 (likely bot) and 1.0 (likely human). The minimum accepted score can be configured via .env:


๐ŸŒฑ Environment Variables (.env)

The library optionally supports .env files via vlucas/phpdotenv. However, it works without .env as well โ€” all variables can be set as standard environment variables or configured directly in code.

Below is a full list of supported environment variables:


Variable Reference

FG_DEFAULT_GET_DEV_ERRORS Globally enables or disables developer error messages across the entire library. When set to false, no dev errors will be returned from any function, regardless of other settings. Each function also accepts a local override for this setting โ€” the local value always takes precedence over the global one.

FG_DEFAULT_SHOW_DEV_ERRORS Controls how developer error messages are delivered globally. When set to true, errors are printed directly on the page. When set to false, they are only returned as a return value from the respective function.

Example: If FG_DEFAULT_GET_DEV_ERRORS=true is set globally but a specific function call has the local override set to false, that function will behave as if dev errors are disabled, while all other functions remain unaffected.

FG_PHONE_FALLBACK_REGIONS Defines the fallback region(s) used during phone number validation when no region is explicitly provided. Accepts a comma-separated list of ISO 3166-1 alpha-2 country codes (e.g. SK,CZ). See Tel Rule Behavior for details.

FG_UPLOAD_PATH Default upload directory for the save validation rule. The path is resolved relative to the project root. Can be overridden per-field by providing a value directly in the rule (e.g. save:uploads/images). See Save Rule Behavior for details.

FG_GOOGLE_APPLICATION_CREDENTIALS Path to the Google service account credentials JSON file used for reCAPTCHA Enterprise authentication. The path is resolved relative to the project root. See Credentials Resolution Order for details.

FG_RECAPTCHA_PROJECT_ID Your Google Cloud project ID used for reCAPTCHA Enterprise. When defined together with FG_RECAPTCHA_SITEKEY, calling captchaInit() is not required. See Google reCAPTCHA Enterprise for details.

FG_RECAPTCHA_SITEKEY Your reCAPTCHA Enterprise site key. When defined together with FG_RECAPTCHA_PROJECT_ID, calling captchaInit() is not required. See Google reCAPTCHA Enterprise for details.

FG_RECAPTCHA_SCORE Minimum accepted reCAPTCHA risk score. Must be a value between 0.0 and 1.0. Values outside this range are automatically clamped. Defaults to 0.5. See Score Threshold for details.


๐Ÿ› Architecture


๐Ÿงช Development & Quality

Dev dependencies:

Code quality standards:


๐Ÿ“Œ Project Status


๐Ÿค Contributing

Pull requests are welcome.

Please:


๐Ÿ”’ Security

If you discover a vulnerability, please open a private issue on GitHub.


๐Ÿ“„ License

MIT License

See LICENSE file for details.


All versions of form-generator with dependencies

PHP Build Version
Package Version
Requires php Version >=8.0
ext-json Version *
google/cloud-recaptcha-enterprise Version ^2.1
vlucas/phpdotenv Version ^5.5
giggsey/libphonenumber-for-php Version ^9.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package scratchwizard1/form-generator contains the following files

Loading the files please wait ...