{"id":22151021,"url":"https://github.com/justcoded/form-handler","last_synced_at":"2025-07-26T04:31:37.436Z","repository":{"id":57003211,"uuid":"117989002","full_name":"justcoded/form-handler","owner":"justcoded","description":"Validate simple html forms requests, send email notifications with ease. Best for pure HTML websites.","archived":false,"fork":false,"pushed_at":"2018-07-31T12:19:29.000Z","size":81,"stargazers_count":15,"open_issues_count":3,"forks_count":10,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-04-18T10:00:09.847Z","etag":null,"topics":["form-handler","form-html","form-processor","form-validation","mandrill-api","php","phpmailer"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/justcoded.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-01-18T13:50:35.000Z","updated_at":"2024-09-25T12:52:26.000Z","dependencies_parsed_at":"2022-08-21T14:10:40.144Z","dependency_job_id":null,"html_url":"https://github.com/justcoded/form-handler","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/justcoded/form-handler","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/justcoded%2Fform-handler","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/justcoded%2Fform-handler/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/justcoded%2Fform-handler/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/justcoded%2Fform-handler/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/justcoded","download_url":"https://codeload.github.com/justcoded/form-handler/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/justcoded%2Fform-handler/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":267117250,"owners_count":24038640,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-07-26T02:00:08.937Z","response_time":62,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["form-handler","form-html","form-processor","form-validation","mandrill-api","php","phpmailer"],"created_at":"2024-12-02T00:29:47.090Z","updated_at":"2025-07-26T04:31:37.165Z","avatar_url":"https://github.com/justcoded.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n    \u003ch1 align=\"center\"\u003eStatic forms FormHandler library\u003c/h1\u003e\n\u003c/p\u003e\n\nSmall library to validate simple html forms data and send requests to email.\nFurthermore you can write your own \"handler\" to process valid data, for example if you need to save\n it through API to a 3d-party service like Mailchimp, SalesForce, CRM system, etc.).\n\n# Why FormHandler\n\nIt's very easy to find some ready-to-use solution to process a contact form. Usually this is pure PHP\nscript, which collect data and send email with php `mail()` function. It's not bad, but you can find\nnumerous problems with such scripts:\n\n* `mail()` function can be blocked on production server, because it's not secure. Also it's often goes to SPAM folder, when you use `mail()` function.\n* You need to validate, that the data is valid. Manual validation of the `$_POST` array is time consuming and require knowledge of PHP, RegExp's, etc. \n\nWe decide to create small library, which fix all these issues, so to process a form you need:\n\n* set validation rules with simple configuration array\n* set your Mail settings (SMTP settings OR Mandrill API key)\n* set your message params (From, To, Subject, Body template)\n\nAnd that's it!\n\n# Requirements\n\n* PHP 7.0+\n* [Composer](http://getcomposer.org/download)\n* Working SMTP server to send emails, or Mandrill account with configured mail domain.\n\n# Usage\n\nImagine you have simple html website with a contact form and you want to process it.\nWe have `name`, `email`, and `message` form fields.  \nWe will guide you through the whole process of creating PHP script to process a form request.\n\n## 1. Init your environment\n\nWe suggest to create separate folder to place code into it. Let's call it `form`. \nFile structure will looks like this:\n\n\t|- /form/        # folder for our code\n\t|- contact.php   # simple HTML page with a form\n\nInside `/form/` folder we need to create `composer.json` file to set our library requirement:\n\n\t{\n        \"require\": {\n            \"justcoded/form-handler\": \"*\"\n        }\n    }\n\nNow we need to download all required files with a composer, by running a bash command:\n\n\tcomposer install\n\n## 2. Entry file\n\nYou must create entry file, which will handle the form request. \nYou can copy one of our examples `examples/basic.php` or `examples/advanced.php` inside package folder.  \n\nLet's call our file `form.php` and create it from scratch. \nIt should be accessible from browser (for example: `http://MY-DOMAIN.COM/form/form.php`).\n\nAfter that you need to include composer autoloader script and then set use part for library classes:\n\n```php\n\u003c?php\n// init autoload.\nrequire __DIR__ . '/vendor/autoload.php';\n\nuse JustCoded\\FormHandler\\FormHandler;\nuse JustCoded\\FormHandler\\Handlers\\MailHandler;\nuse JustCoded\\FormHandler\\DataObjects\\MailMessage;\nuse JustCoded\\FormHandler\\FileManager\\FileManager;\n```\n\n## 3. Form processing\n\nForm processing idea is super easy. We have main `FormHandler` object, which will validate data and \nrun some handler (right now we have only one Handler - email sender). And as the result we can get info\nabout errors found during the whole process.\n\nAll this code is placed at the end of the `form.php` and looks like this:\n\n```php\n$mailer = new MailHandler($mailerConfig, new MailMessage($messageConfig));\n$form = new FormHandler($validationRules, $mailer);\n\nif ($form-\u003evalidate($_POST)) {\n\t$form-\u003eprocess();\n}\n\n$result = $form-\u003eresponse();\n\n// TODO: do somethign with the results. For example write to a session and redirect back.\n```\n\n## 4. Set Configurations\n\nAs you can see above we need to set 3 configuration arrays:\n\n* `$validationRules` - defines validation rules and messages\n* `$mailerConfig` - defines mailer component (PHPMailer or Mailchimp) and it's params\n* `$messageConfig` - defines From/To/Body fields\n\n### 4.1. Validation Rules\n\nFor validation we use popular [Valitron](https://github.com/vlucas/valitron) PHP library. We use \n`mapFieldsRules()` method to set fields rules and `labels()` method to set field labels to show\nerror messages correctly. So what you need to do is to set `'fields'` and `'labels'` keys in \n`$validationRules` array:\n\n \n```php\n$validationRules = [\n\t'fields' =\u003e [\n\t\t'name' =\u003e ['required'],\n\t\t'email' =\u003e ['required', 'email'],\n\t\t'message' =\u003e [\n\t\t\t'required',\n\t\t\t['lengthMin', 5]\n\t\t],\n\t], // according to Valitron doc for mapFieldsRules().\n\t'labels' =\u003e [\n\t\t'name'  =\u003e 'Name',\n\t\t'email' =\u003e 'Email address',\n\t\t'message' =\u003e 'Message',\n\t] // according to Valitron doc for labels().\n];\n```\n\n### 4.2. Mailer Config\n\nThere are two options for Mailer: [PHPMailer](https://github.com/PHPMailer/PHPMailer) and implementation\nof [Mandrill API](https://mandrillapp.com/api/docs/).\n\n* PHPMailer is used to send through `SMTP` protocol or PHP `mail()` function.\n* Mandrill API is used to send through [Mandrill](https://www.mandrill.com/) mail service using it's API.  \n\nBelow you can find examples of configuration arrays for both methods:\n\n```php\n// PHPMailer config:\n$mailerConfig = [\n\t'mailer'   =\u003e MailHandler::USE_PHPMAILER,\n\t'host'     =\u003e 'SMTP HOST',     // set your smtp host.\n\t'user'     =\u003e 'YOUR EMAIL',    // set email.\n\t'password' =\u003e 'YOUR PASSWORD', // set password.\n\t'protocol' =\u003e 'tls',           // 'tls', 'ssl' or FALSE for not secure protocol/\n\t'port'     =\u003e 587,             // your port.\n];\n\n// Mandrill config:\n$mailerConfig = [\n\t'mailer'   =\u003e MailHandler::USE_MANDRILL,\n\t'apiKey' =\u003e 'YOUR API KEY',  // set correct API KEY.\n];\n```\n\n### 4.3. Message configuration\n\nThe latest configuration you have to set is options for your email: From, To addresses; Subject and Body.\nOptional you can set CC and BCC headers as well.\n\nExample:\n\n```php\n$messageConfig = [\n    'from' =\u003e ['noreply@my-domain.com' =\u003e 'My Domain Support'],\n    'to' =\u003e ['admin@my-domain.com' =\u003e 'John Doe'],\n    'replyTo' =\u003e ['REPLY.EMAIL@DOMAIN.COM' =\u003e 'REPLY NAME'],     // OPTIONAL\n    'cc'      =\u003e ['cc-email@gmail.com', 'more-cc@gmail.com'],    // OPTIONAL\n    'bcc'     =\u003e ['bcc-email@gmail.com'],                        // OPTIONAL\n    'subject' =\u003e 'Contact request from {name}',\n    'bodyTemplate' =\u003e __DIR__ . '/template-html.php',        // Path to HTML template\n    'altBodyTemplate' =\u003e __DIR__ . '/template-plain.php',    // Path to TEXT template\n];\n```\n\nFor each address field you can set numerous emails in such format:\n\n\t[ email1 =\u003e name1, email2 =\u003e name2, ... ]\n\tOR\n\t[email1, email2, email3 ...]\n\n`bodyTemplate` and `altBodyTemplate` are paths to usual PHP template files, which will be used to generate\nemail message (HTML and plain versions accordingly).\n\n## 5. All together\n\nIf we combine all parts we can get file similar to this one:\n\n```php\n\u003c?php\n\n// init autoload.\nrequire __DIR__ . '/../vendor/autoload.php';\n\nuse JustCoded\\FormHandler\\FormHandler;\nuse JustCoded\\FormHandler\\Handlers\\MailHandler;\nuse JustCoded\\FormHandler\\DataObjects\\MailMessage;\n\n$validationRules = [\n\t'fields' =\u003e [\n\t\t'name' =\u003e ['required'],\n\t\t'email' =\u003e ['required', 'email'],\n\t\t'message' =\u003e [\n\t\t\t'required',\n\t\t\t['lengthMin', 5]\n\t\t],\n\t], // according to Valitron doc for mapFieldsRules.\n\t'labels' =\u003e [\n\t\t'name'  =\u003e 'Name',\n\t\t'email' =\u003e 'Email address',\n\t\t'message' =\u003e 'Message',\n\t] // according to Valitron doc.\n];\n\n// SMTP config.\n$mailerConfig = [\n\t'mailer'   =\u003e MailHandler::USE_PHPMAILER,\n\t'host'     =\u003e 'SMTP HOST',     // set your smtp host.\n\t'user'     =\u003e 'YOUR EMAIL',    // set email.\n\t'password' =\u003e 'YOUR PASSWORD', // set password.\n\t'protocol' =\u003e 'tls',           // 'tls', 'ssl' or FALSE for not secure protocol/\n\t'port'     =\u003e 587,             // your port.\n];\n\n// Message settings.\n$messageConfig = [\n\t'from' =\u003e ['FROM.EMAIL@DOMAIN.COM' =\u003e 'FROM NAME'],     // set correct FROM.\n\t'to' =\u003e ['TO.EMAIL@DOMAIN.COM' =\u003e 'TO NAME'],           // set correct TO.\n\t'replyTo' =\u003e ['REPLY.EMAIL@DOMAIN.COM' =\u003e 'REPLY NAME'],// set correct REPLY.\n\t'subject' =\u003e 'Contact request from {name}',\n\t'bodyTemplate' =\u003e __DIR__ . '/template-html.php',\n\t'altBodyTemplate' =\u003e __DIR__ . '/template-plain.php',\n];\n\n// Run processing.\n$mailer = new MailHandler($mailerConfig, new MailMessage($messageConfig));\n$form   = new FormHandler($validationRules, $mailer);\n\nif ($form-\u003evalidate($_POST)) {\n\t$form-\u003eprocess();\n}\n\n// write errors and return back.\nsetcookie('basic_response', $form-\u003eresponse());\nheader('Location: index.php');\nexit;\n```\n\nIn this example we write errors to cookies to be able to get them on the HTML page via JavaScript or PHP code.\n\n## 6. Body templates\n\nTemplates are usual PHP files, which can print any PHP code you leave inside. However to make editing\neasier we added tokens support. So any keys, which are passed as data to FormHandler can be used as a \ntoken like this: `{key}`.\n\n**template-html.php** example:\n```html\n\u003c?php\n/* @var array $data */\n?\u003e\n\u003chtml\u003e\n\u003cbody\u003e\n\u003cp\u003eHi John,\u003c/p\u003e\n\u003cp\u003eSomeone submitted a contact form on your site with such data:\u003c/p\u003e\n\u003cp\u003e\u003cb\u003eName:\u003c/b\u003e {name}\u003c/p\u003e\n\u003cp\u003e\u003cb\u003eEmail:\u003c/b\u003e {email}\u003c/p\u003e\n\u003cp\u003e\u003cb\u003eMessage:\u003c/b\u003e\u003cbr\u003e\n\t{message}\u003c/p\u003e\n\n\u003chr\u003e\n\u003cp\u003eUser IP address: \u003c?php echo @$_SERVER['REMOTE_ADDR']; ?\u003e\u003c/p\u003e\n\u003cp\u003eBrowser: \u003c?php echo @$_SERVER['HTTP_USER_AGENT']; ?\u003e\u003c/p\u003e\n\n\u003c/body\u003e\n\u003c/html\u003e\n``` \n\n**template-plain.php** example:\n```php\n\u003c?php\n/* @var array $data */\n?\u003e\nHi John,\nSomeone submitted a contact form on your site with such data:\n\nName:    {name}\nEmail:   {email}\nSubject: {subject}\nMessage:\n\n\t{message}\n\n-------\n\nUser IP address: \u003c?php echo @$_SERVER['REMOTE_ADDR']; ?\u003e\nBrowser: \u003c?php echo @$_SERVER['HTTP_USER_AGENT']; ?\u003e\n```\n\n## Response formats\n\nFormHandler can return response as ARRAY or as JSON. By default it return a JSON string. \nTo change this behavior you need to add one more parameter to FormHandler object creation:\n\n```php\n$form   = new FormHandler($validationRules, $mailer, 'array');\n```  \n\nOnce you get a response, you need to pass it to the page with a form to show errors. This can be done\nin several ways:\n\n### Pass response as JSON object\n\nWe recommend to send form request with AJAX request. In this case you will need single JSON object as\nserver side response:\n\n```php\n// print errors as json.\nheader('Content-Type: application/json; charset=utf-8');\necho $formHandler-\u003eresponse();\nexit;\n```\n\n### Pass response through COOKIES\n\nIf you use cookies - you can use JavaScript to display errors on the site and don't need PHP knowledge\nin this case.\n\n```php\n// set cookie with form status/errors and redirect back\nsetcookie('form_status', $form-\u003eresponse());\nheader('Location: index.php');\nexit;\n```\n\n### Pass response through SESSION\n\nIn case you want to process errors with PHP code - then better option of passing errors is using\n a session:\n\n```php\n// start session if not started:\nsession_start();\n// set sesson with form status/errors and redirect back\n$_SESSION['form_status'] = $form-\u003eresponse();\nheader('Location: index.php');\nexit;\n```\n\n### Response array\n\nIn case of success\n```json\n{\"status\":true,\"errors\":[]}\n```\n\nIn case of errors:\n```json\n{\"status\":false,\"errors\":{\"field1\": [\"Error1\", \"Error2\"], \"field2\": [\"Error3\", \"Error4\"]}}\n```\n\n## File uploads and mail attachments\n\nForm handler also supports File uploads and sending them as email attachments.\n\nTo add this feature you will need one more class, called `FileManager`:\n\n```php\n// Configure the location of attachments directory \n// it should be writable and accessible from browser\n$fileManager = new FileManager([\n    'uploadPath' =\u003e __DIR__ . '/attachments',           // folder path to save files to \n    'uploadUrl' =\u003e 'http://MY-DOMAIN.COM/attachments',  // site URL to this folder\n]);\n```\n\nAfter that you need to specify which files should be uploaded in `$messageConfig`:\n\n```php\n$messageConfig = [\n\t'from' =\u003e ['FROM.EMAIL@DOMAIN.COM' =\u003e 'FROM NAME'],     // set correct FROM.\n\t'to' =\u003e ['TO.EMAIL@DOMAIN.COM' =\u003e 'TO NAME'],           // set correct TO.\n\t'replyTo' =\u003e ['REPLY.EMAIL@DOMAIN.COM' =\u003e 'REPLY NAME'],// set correct REPLY.\n\t'subject' =\u003e 'Contact request from {name}',\n\t'bodyTemplate' =\u003e __DIR__ . '/template-html.php',\n\t'altBodyTemplate' =\u003e __DIR__ . '/template-plain.php',\n\t\n    'attachments' =\u003e $fileManager-\u003eupload([\n        'input_file_name1', 'input_file_name2', // ...\n    ])\n];\n```\n\n`input_file_name1`, `input_file_name2` are the name attributes of file inputs:\n\n```html\n\u003cinput type=\"file\" name=\"input_file_name1\"\u003e\n\u003cinput type=\"file\" name=\"input_file_name2\"\u003e\n...\n```\n\nOf course each mail server has a limit of maximum attachments size. Usually it's not more than 10MB.\nTo set this limit correctly you need to update `$mailerConfig` with additional option:\n\n```php\n$mailerConfig = [\n\t'mailer'   =\u003e MailHandler::USE_PHPMAILER, // or USE_MANDRILL\n\t...\n\n\t'attachmentsSizeLimit' =\u003e 8388608, // 8MB in Bytes.\n];\n```\n\nAll attachments are uploaded to the specified directory and we recommend to add links to them inside\nbody/alternativeBody templates. To print file link to a file you need to write a token with input\nfile name. Like this:\n\n```php\n...\n\u003cp\u003eAttachments: {input_file_name1}, {input_file_name2}\u003c/p\u003e\n...\n```\n\nIf you need to validate your file with specific type or size you can use our custom \"file\" validator:\n\n```php\n$validationRules = [\n\t'fields' =\u003e [\n\t\t// ...\n\t\t'input_file_name1' =\u003e [  // this is file field.\n\t\t\t[\n\t\t\t\t'file',\n\t\t\t\t['jpeg', 'jpg', 'png', 'pdf'], // types.\n\t\t\t\t2000000,                       // size limit around 2 MB.\n\t\t\t\t'message' =\u003e '{field} should be up to 2MB and allows only file types jpeg, png.',\n\t\t\t],\n\t\t],\n\t\t...\n];\n```\n\n## Multiple fields\n\nSome forms may have multiple fields, like checkboxes, multiple selects or dynamically created inputs.\n\nExample:\n\n```html\n\u003c!-- multiple select --\u003e\n\u003cselect name=\"choice\" multiple\u003e\n\t\u003coption value=\"1\"\u003e1\u003c/option\u003e\n\t\u003coption value=\"2\"\u003e2\u003c/option\u003e\n\t\u003coption value=\"3\"\u003e3\u003c/option\u003e\n\u003c/select\u003e\n\n\u003c!-- text inputs --\u003e\n\u003cinput type=\"text\" name=\"links[]\"\u003e\n\u003cinput type=\"text\" name=\"links[]\"\u003e\n\u003cinput type=\"text\" name=\"links[]\"\u003e\n```\n\nYou can validate each input using wildcard field name inside **validation rules*:\n\n```php\n$validationRules = [\n\t'fields' =\u003e [\n\t\t// ...\n\t\t'choice.*' =\u003e ['int'],\n\t\t'links.*'  =\u003e ['url'],\n\t\t...\n];\n```\n\nSame as file attachments you can use tokens to print all values at once. They will be comma separated.\n\n**Template usage:**\n\n```html\n...\n\u003cp\u003eChoice: {choice}\u003c/p\u003e\n\u003cp\u003eLinks: {links}\u003c/p\u003e\n```\n\n# Examples\n\nYou can check working examples inside `examples` folder of the package, start your investigate from `index.php` file (contains forms HTML).\nThere you can find which files loaded next, when you submit forms.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjustcoded%2Fform-handler","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjustcoded%2Fform-handler","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjustcoded%2Fform-handler/lists"}