PHP Beginners Guide
Welcome to PHP Form Builder's Beginners Guide
Here you'll learn in a few steps how to:
- Install and run a local PHP server
- Check your PHP version
- Include the required files on your page to build your form
- Register your copy
- Build your first form
- Validate user's posted values and send email
- Complete page code
- To go further
For any question or request
Please
- contact me through PHP Form Builder's comments on Codecanyon
- Email me at https://www.miglisoft.com/#contact
Check your PHP version
-
Create a new empty file at the root of your project, named, for example, test-form.php.
-
Add the following line to your file:
<?php phpinfo(); ?>
-
Open your favorite browser and go to your file's URL, for example, http://localhost/test-form.php
-
If your version is PHP 7.4 or newer, you're on the right track.
If not, you've got to upgrade your PHP to a more recent version.
Upload the phpformbuilder folder
-
Add the phpformbuilder folder at the root of your project.
Your directory structure should be similar to this:
PHP Form Builder's package includes the Form Builder itself, the documentation, and the templates.
Documentation and Templates are available online at https://www.phpformbuilder.pro/.
There's no need to upload them on your production server.More details about folders, files, and required files on the production server are available here: ../#package-structure
Register
Open phpformbuilder/register.php in your browser, and enter your purchase code to activate your copy.
Each purchased license allows the installation of PHP Form Builder on two different domains:
- One for localhost
- One for your production server
Once you register your purchase, delete register.php from your production server to avoid unwanted access.
Include required files on your page to build the form
-
Open the test-form.php you created on step n°2 with your favorite editor (VS-Code, Sublime Text, Notepad++, Atom, ...)
-
Add HTML basic markup:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Test Form</title> <!-- Bootstrap 5 CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> </head> <body> <h1>My first form</h1> <!-- Bootstrap 5 JavaScript --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> </body> </html>
-
Now add the following code at the very beginning of your file:
<?php use phpformbuilder\Form; use phpformbuilder\Validator\Validator; /* ============================================= Start session and include the autoloader ============================================= */ session_start(); include_once rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR) . '/phpformbuilder/autoload.php'; ?>
<?php // Following 2 lines are required since PHP 5.3 to set namespaces. // more details here: http://php.net/manual/en/language.namespaces.php use phpformbuilder\Form; use phpformbuilder\Validator\Validator; // Following line starts PHP session. That's to say we'll memorize variables in PHP session. session_start(); // Then we include the autoloader. include_once rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR) . '/phpformbuilder/autoload.php'; ?>
-
Refresh your test-form.php in your browser (http://localhost/my-project/test-form.php)
If you see a blank page, all is ok, you can go on to next step
If your browser throws an error 500, click button below to solve this.
Your browser has thrown this error because PHP can't find phpformbuilder/autoload.php.
rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR)
should lead to the root of your project.
If works fine if your server is well configured, but it seems that's not the case.To solve this, open ../phpformbuilder/server.php in your browser and follow the instructions.
More explainations about error 500 are available at https://www.phpformbuilder.pro/documentation/help-center.php#warning-include_once
Build your first form
So let's start building the form.
-
To create a new form, add this line just after the
include_once
statement Line 5 in your test-form.php:$form = new Form('test-form', 'horizontal', 'novalidate');
$form = new Form('test-form', 'horizontal', 'novalidate'); // this function creates a new form object. // arguments: // 'test-form' : this is the form name // 'horizontal': this will add class="form-horizontal" // 'novalidate': this will add 'novalidate' attribute. It prevents browser to use browser's html5 built-in validation. // You can skip 'novalidate' argument if you want to use browser's html5 built-in validation. // If you want Material Design style, instanciate this way: $form = new Form('test-form', 'horizontal', 'novalidate', 'material'); // or with html5 validation: $form = new Form('test-form', 'horizontal', '', 'material');
-
Add the following line to create an input field:
$form->addInput('text', 'user-name', '', 'Name:', 'required, placeholder=Name');
$form->addInput('text', 'user-name', '', 'Name:', 'required, placeholder=Name'); // this function adds an input to your form. // arguments: // 'text' : the html input type. can be for example 'text' or 'hidden', 'email', 'number', ... // 'user-name': the html "name" attribute // 'Name:' : label content displayed on screen // 'required, placeholder=Name': can be any html addributes, separated with commas and without quotes.
-
Add the following line to create 2 radio buttons with Nice Check plugin
$form->addRadio('is-all-ok', 'Yes', 1); $form->addRadio('is-all-ok', 'No', 0); $form->printRadioGroup('is-all-ok', 'Is all ok?', false, 'required'); $form->addPlugin('nice-check', '#test-form', 'default', ['skin' => 'red']);
// add 2 radio buttons. // arguments: // 'is-all-ok' : radio groupname // 'Yes' : radio label // 1 : radio value $form->addRadio('is-all-ok', 'Yes', 1); $form->addRadio('is-all-ok', 'No', 0); // render radio group // arguments: // 'is-all-ok' : radio groupname // 'Is all ok?': radio group label // false : inline (true or false) // 'required' : this will add 'required' attribute. can contain any html attribute(s), separated with commas. $form->printRadioGroup('is-all-ok', 'Is all ok?', false, 'required'); // Add Nice Check plugin (beautiful radio buttons) // arguments: // 'input' : plugin's target (JavaScript selector) // 'default': plugin's config (see class doc for details please) // array([...]) : arguments sended to plugin (see class doc for details please) $form->addPlugin('nice-check', '#test-form', 'default', ['skin' => 'red']);
-
Add the submit button:
$form->addBtn('submit', 'submit-btn', 1, 'Send', 'class=btn btn-success');
$form->addBtn('submit', 'submit-btn', 1, 'Send', 'class=btn btn-success'); // this function adds a button to your form. // arguments: // 'submit' : the html button type. // 'submit-btn' : the html "name" attribute // 'Send:' : Button text content displayed on screen // 'class=btn btn-success': can be any html addributes, separated with commas and without quotes.
-
Well done. Now the form is ready with an input and a submit button.
Last step is to render it on page.We'll add 3 PHP blocks.
-
Just before
</head>
:<?php $form->printIncludes('css'); ?>
-
Anywhere between
<body></body>
: (at the place you want the form to be displayed)<?php if (isset($sentMessage)) { echo $sentMessage; } $form->render(); ?>
-
Just before
</body>
:<?php $form->printIncludes('js'); $form->printJsCode(); ?>
// Following lines will include JavaScript plugin's css files if your form uses plugins. <?php $form->printIncludes('css'); ?> // following lines will render the form in your page, and display success / error message if form has been posted by user. <?php if (isset($sentMessage)) { echo $sentMessage; } $form->render(); ?> // Following lines will include JavaScript plugin's js files if your form uses plugins. <?php $form->printIncludes('js'); ?>
-
-
Refresh your test-form.php in your browser (http://localhost/my-project/test-form.php)
your form should be displayed.
Validate the user's posted values and send emails
Add this PHP block just after include_once [...] . '/phpformbuilder/autoload.php';
:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// create validator & auto-validate required fields
$validator = Form::validate('test-form');
// check for errors
if ($validator->hasErrors()) {
$_SESSION['errors']['test-form'] = $validator->getAllErrors();
} else {
$emailConfig = array(
'sender_email' => 'contact@my-site.com',
'sender_name' => 'PHP Form Builder',
'recipient_email' => 'recipient-email@my-site.com',
'subject' => 'PHP Form Builder - Test form email',
'filter_values' => 'test-form'
);
$sentMessage = Form::sendMail($emailConfig);
Form::clear('test-form');
}
}
// if form has been posted
if ($_SERVER["REQUEST_METHOD"] == "POST" && Form::testToken('test-form') === true) {
// create a new validator object & auto-validate required fields
$validator = Form::validate('test-form');
// store errors in session if any
if ($validator->hasErrors()) {
$_SESSION['errors']['test-form'] = $validator->getAllErrors();
} else {
// all is ok, send email
// PHP Form Builder will add all posted labels and values to your message,
// no need to do anything manually.
$emailConfig = array(
'sender_email' => 'contact@my-site.com',
'sender_name' => 'PHP Form Builder',
'recipient_email' => 'recipient-email@my-site.com',
'subject' => 'PHP Form Builder - Test form email',
// filter_values are posted values you don't want to include in your message. Separated with commas.
'filter_values' => 'test-form'
);
// send message
$sentMessage = Form::sendMail($emailConfig);
// clear session values: next time your form is displayed it'll be emptied.
Form::clear('test-form');
}
}
Complete page code
<?php
use phpformbuilder\Form;
use phpformbuilder\Validator\Validator;
/* =============================================
Start session and include the autoloader
============================================= */
session_start();
include_once rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR) . '/phpformbuilder/autoload.php';
if ($_SERVER["REQUEST_METHOD"] == "POST" && Form::testToken('test-form') === true) {
// create validator & auto-validate required fields
$validator = Form::validate('test-form');
// check for errors
if ($validator->hasErrors()) {
$_SESSION['errors']['test-form'] = $validator->getAllErrors();
} else {
$emailConfig = array(
'sender_email' => 'contact@my-site.com',
'sender_name' => 'PHP Form Builder',
'recipient_email' => 'recipient-email@my-site.com',
'subject' => 'PHP Form Builder - Test form email',
// filter_values are posted values you don't want to include in your message. Separated with commas.
'filter_values' => 'test-form'
);
// send message
$sentMessage = Form::sendMail($emailConfig);
Form::clear('test-form');
}
}
$form = new Form('test-form', 'horizontal', 'novalidate');
$form->addInput('text', 'user-name', '', 'Name:', 'required, placeholder=Name');
$form->addRadio('is-all-ok', 'Yes', 1);
$form->addRadio('is-all-ok', 'No', 0);
$form->printRadioGroup('is-all-ok', 'Is all ok?', false, 'required');
$form->addPlugin('nice-check', '#test-form', 'default', ['skin' => 'red']);
$form->addBtn('submit', 'submit-btn', 1, 'Send', 'class=btn btn-success');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Test Form</title>
<!-- Bootstrap 5 CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<?php $form->printIncludes('css');?>
</head>
<body>
<h1>My first form</h1>
<?php
if (isset($sentMessage)) {
echo $sentMessage;
}
$form->render();
?>
<!-- Bootstrap 5 JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<?php
$form->printIncludes('js');
$form->printJsCode();
?>
</body>
</html>
To go further
Now you've learned the basics; Several resources will help to add other fields, plugins, validate different values and build more complex layouts: