Package: Zebra_Form

Class: Zebra_Form

source file: /Zebra_Form.php

Class Overview


Zebra_Form, a jQuery augmented PHP library for creating and validating HTML forms

It provides an easy and intuitive way of creating template-driven, visually appealing forms, complex client-side and server-side validations and prevention against cross-site scripting (XSS) and cross-site request forgery (CSRF) attacks prevention.

For the form validation part you can use the built-in rules (i.e. required fields, emails, minimum/maximum length, etc) and you can also define custom rules, with extreme ease, depending on your specific needs.

All the basic controls that you would find in a form are available plus a few extra: text, textarea, submit, image, reset, button, file, password, radio buttons, checkboxes, hidden, captcha, date and time pickers.

One additional note: this class is not a drag and drop utility - it is intended for coders who are comfortable with PHP, HTML, CSS and JavaScript/jQuery - you will have to build your forms when using this class, but it saves a great deal of time when it comes to validation and assures that your forms are secure and have a consistent look and feel throughout your projects!

Requires PHP 5.0.2+ (compiled with the php_fileinfo extension), and jQuery 1.6.2+

Visit http://stefangabos.ro/php-libraries/zebra-form/ for more information.

For more resources visit http://stefangabos.ro/

Author(s):

Version:

  • 2.9.4 (last revision: December 21, 2013)

Copyright:

  • (c) 2006 - 2013 Stefan Gabos

Class properties

array $file_upload

An associative array of items uploaded to the current script via the HTTP POST method.

This property, available only if a file upload has occurred, will have the same values as $_FILES plus some extra values:

  • path - the path where the file was uploaded to
  • file_name - the name the file was uploaded with
  • imageinfo - available only if the uploaded file is an image!
    an array of attributes specific to the uploaded image as returned by getimagesize() but with meaningful names:
    bits
    channels
    mime
    width
    height
    type (possible types)
    html

Note that the file name can be different than the original name of the uploaded file!

By design, the script will append a number to the end of a file's name if at the path where the file is uploaded to there is another file with the same name (for example, if at the path where a file named "example.txt" is uploaded to, a file with the same name exists, the file's new name will be "example1.txt").

The file names can also be random-generated. See the set_rule() method and the upload rule

Top

string $file_upload_permissions

Indicates the filesystem permissions to be set for files uploaded through the upload rule.

  1. $form->file_upload_permissions '0777';

The permissions are set using PHP's chmod function which may or may not be available or be disabled on your environment. If so, this action will fail silently (no errors or notices will be shown by the library).

Better to leave this setting as it is.

If you know what you are doing, here is how you can calculate the permission levels:

  • 400 Owner Read
  • 200 Owner Write
  • 100 Owner Execute
  • 40 Group Read
  • 20 Group Write
  • 10 Group Execute
  • 4 Global Read
  • 2 Global Write
  • 1 Global Execute

Default is '0755'

Top

Class methods

constructor __construct()

void __construct ( string $name , [ string $method = 'POST'] , [ string $action = ''] , [ array $attributes = ''] )

Constructor of the class

Initializes the form.

  1. $form new Zebra_Form('myform');
Parameters:
string $name Name of the form
string $method

(Optional) Specifies which HTTP method will be used to submit the form data set.

Possible (case-insensitive) values are POST an GET

Default is POST

string $action

(Optional) An URI to where to submit the form data set.

If left empty, the form will submit to itself.

You should *always* submit the form to itself, or server-side validation will not take place and you will have a great security risk. Submit the form to itself, let it do the server-side validation, and then redirect accordingly!

array $attributes

(Optional) An array of attributes valid for a <form> tag (i.e. style)

Note that the following attributes are automatically set when the control is created and should not be altered manually:

action, method, enctype, name

Top

method add()

reference & add ( string $type , mixed $arguments )

Adds a control to the form.

  1. //  create a new form
  2. $form new Zebra_Form('my_form');
  3.  
  4. // add a text control to the form
  5. $obj $form->add('text''my_text');
  6.  
  7. // make the text field required
  8. $obj->set_rule(
  9.      'required' => array(
  10.         'error',            // variable to add the error message to
  11.         'Field is required' // error message if value doesn't validate
  12.      )
  13. );
  14.  
  15. // don't forget to always call this method before rendering the form
  16. if ($form->validate()) {
  17.     // put code here
  18. }
  19.  
  20. //  output the form using an automatically generated template
  21. $form->render();
Tags:
return: Returns a reference to the newly created object
Parameters:
string $type

Type of the control to add.

Controls that can be added to a form:

mixed $arguments A list of arguments as required by the control that is added.
Top

method add_error()

void add_error ( string $error_block , string $error_message )

Appends a message to an already existing error block

  1. //  create a new form
  2. $form new Zebra_Form('my_form');
  3.  
  4. // add a text control to the form
  5. $obj $form->add('text''my_text');
  6.  
  7. // make the text field required
  8. $obj->set_rule(
  9.      'required' => array(
  10.         'error',            // variable to add the error message to
  11.         'Field is required' // error message if value doesn't validate
  12.      )
  13. );
  14.  
  15. // don't forget to always call this method before rendering the form
  16. if ($form->validate()) {
  17.  
  18.     // for the purpose of this example, we will do a custom validation
  19.     // after calling the "validate" method.
  20.     // for custom validations, using the "custom" rule is recommended instead
  21.  
  22.     // check if value's is between 1 and 10
  23.     if ((int)$_POST['my_text']|| (int)$_POST['my_text']10{
  24.  
  25.         $form->add_error('error''Value must be an integer between 1 and 10!');
  26.  
  27.     else {
  28.  
  29.         // put code here that is to be executed when the form values are ok
  30.  
  31.     }
  32.  
  33. }
  34.  
  35. //  output the form using an automatically generated template
  36. $form->render();
Parameters:
string $error_block The name of the error block to append the error message to (also the name of the PHP variable that will be available in the template file).
string $error_message The error message to append to the error block.
Top

method assets_path()

void assets_path ( string $server_path , string $url )

Set the server path and URL to the "process.php" and "mimes.json" files.

These files are required for CAPTCHAs and uploads.

By default, the location of these files is in the same folder as Zebra_Form.php and the script will automatically try to determine both the server path and the URL to these files. However, when the script is run on a virtual host, or if these files were moved, the script may not correctly determine the paths to these files. In these instances, use this method to correctly set the server path - needed by the script to correctly include these files, and the URL - needed by the client-side validation to include these files.

Also, for security reasons, I recommend moving these two files by default to the root of your website (or another publicly accessible place) and manually set the paths, in order to prevent malicious users from finding out information about your directory structure.

If you move these files don't forget to also move the font file from the "includes" folder, and to manually adjust the path to the font file in "process.php"!

Parameters:
string $server_path

The server path (the one similar to what is in $_SERVER['DOCUMENT_ROOT']) to the folder where the "process.php" and "mimes.json" files can be found.

With trailing slash!

string $url

The URL to where the "process.php" and "mimes.json" files can be found.

With trailing slash!

Top

method assign()

void assign ( string $variable_name , mixed $value )

Creates a PHP variable with the given value, available in the template file.

  1. //  create a new form
  2. $form new Zebra_Form('my_form');
  3.  
  4. // make available the $my_value variable in the template file
  5. $form->assign('my_value''100');
  6.  
  7. // don't forget to always call this method before rendering the form
  8. if ($form->validate()) {
  9.     // put code here
  10. }
  11.  
  12. // output the form
  13. // notice that we are using a custom template
  14. // my_template.php file is expected to be found
  15. // and in this file, you may now use the $my_value variable
  16. $form->render('my_template.php');
Parameters:
string $variable_name Name by which the variable will be available in the template file.
mixed $value The value to be assigned to the variable.
Top

method auto_fill()

void auto_fill ( [ array $defaults = array()] , [ boolean $specifics_only = false] )

Call this method anytime *before* calling the render() method to instruct the library to automatically fill out all of the form's fields with random content while obeying any rules that might be set for each control.

You can also use this method to set defaults for the form's elements by setting the method's second argument to TRUE.

Notes:

  • unless overridden, the value of password controls will always be "12345678";
  • unless overridden, the value of controls having the "email" or "emails" rule set will be in the form of random_text@random_text.com;
  • unless overridden, the value of controls having the "url" rule set will be in the form of random_text.com, prefixed or not with "http://", depending on the rule's attributes;
  • file upload controls and controls having the "captcha" or "regexp" rule set will *not* be autofilled;
This method will produce results *only* if the form has not yet been submitted! Also, this method will fill elements with random content *only* if the element does not already has a default value! And finally, this method will produce no results unless at some point the form's validate() method is called.

Tags:
since: 2.8.9
Parameters:
array $defaults

An associative array in the form of $element => $value used for filling out specific fields with specific values instead of random ones.

For elements that may have more than one value (checkboxes and selects with the "multiple" attribute set) you may set the value as an array.

  1. // auto-fill all fields with random values
  2. $form->auto_fill();
  3.  
  4. // auto-fill all fields with random values
  5. // except the one called "email" which should have a custom value
  6. $form->auto_fill(array(
  7.     'email'     =>  'some@email.com',
  8. ));
  9.  
  10. // auto-fill all fields with random values
  11. // except a checkboxes group where we select multiple values
  12. // note that we use "my_checkboxes" insteas of "my_checkboxes[]"
  13. // (the same goes for "selects" with the "multiple" attribute set)
  14. $form->auto_fill(array(
  15.     'my_checkboxes' =>  array('value_1''value_2'),
  16. ));
boolean $specifics_only

(Optional) If set to TRUE only the fields given in the $defaults argument will be filled with the given values and the other fields will be skipped.

Can be used as a handy shortcut for giving default values to elements instead of putting default values in the constructor or using the set_attributes() method.

Default is FALSE.

Top

method captcha_storage()

void captcha_storage ( string $method )

Sets the storage method for CAPTCHA values.

By default, captcha values are triple md5 hashed and stored in cookies, and when the user enters the captcha value the value is also triple md5 hashed and the two values are then compared.

Sometimes, your users may have a very restrictive cookie policy and so cookies will not be set, and therefore, they will never be able to get past the CAPTCHA control. If it's the case, call this method and set the storage method to "session".

In this case, call this method and set the the storage method to "session".

Tags:
since: 2.8.9
Parameters:
string $method

Storage method for CAPTCHA values.

Valid values are "cookie" and "session".

Default is "cookie".

Top

method clientside_validation()

void clientside_validation ( mixed $properties )

Sets properties for the client-side validation.

Client-side validation, when enabled, occurs on the "onsubmit" event of the form.

  1. //  create a new form
  2. $form new Zebra_Form('my_form');
  3.  
  4. // disable client-side validation
  5. $form->clientside_validation(false);
  6.  
  7. // enable client-side validation using default properties
  8. $form->clientside_validation(true);
  9.  
  10. // enable client-side validation using customized properties
  11. $form->clientside_validation(array(
  12.     'close_tips'                =>  false,      //  don't show a "close" button on tips with error messages
  13.     'on_ready'                  =>  false,      //  no function to be executed when the form is ready
  14.     'disable_upload_validation' =>  true,       //  using a custom plugin for managing file uploads
  15.     'scroll_to_error'           =>  false,      //  don't scroll the browser window to the error message
  16.     'tips_position'             =>  'right',    //  position tips with error messages to the right of the controls
  17.     'validate_on_the_fly'       =>  false,      //  don't validate controls on the fly
  18.     'validate_all'              =>  false,      //  show error messages one by one upon trying to submit an invalid form
  19. ));

To access the JavaScript object and use the public methods provided by it, use $('#formname').data('Zebra_Form') where formname is the form's name with any dashes turned into underscores!

Therefore, if a form's name is "my-form", the JavaScript object would be accessed like $('my_form').data('Zebra_Form').

From JavaScript, these are the methods that can be called on this object:

  • attach_tip(element, message) - displays a custom error message, attached to the element with the indicated ID (so, remember, "element" is string, not an object!)
  • clear_errors() - hides all error messages;
  • submit() - submits the form;
  • validate() - checks if the form is valid; returns TRUE or FALSE;

Here's how you can use these methods, in JavaScript:

  1. //  let's submit the form when clicking on a random button
  2.  
  3. // get a reference to the Zebra_Form object
  4. var $form = $('#formname').data('Zebra_Form');
  5.  
  6. // handle the onclick event on a random button
  7. $('#somebutton').bind('click'function(e{
  8.  
  9.     // stop default action
  10.     e.preventDefault();
  11.  
  12.     // validate the form, and if the form validates
  13.     if ($form.validate()) {
  14.  
  15.         // do your thing here
  16.  
  17.         // when you're done, submit the form
  18.         $form.submit();
  19.  
  20.     }
  21.  
  22.     // if the form is not valid, everything is handled automatically by the library
  23.  
  24. });
Parameters:
mixed $properties

Can have the following values:

  • FALSE, disabling the client-side validation; Note that the dependencies rule will still be checked client-side so that callback functions get called, if it is the case!
  • TRUE, enabling the client-side validation with the default properties;

  • an associative array with customized properties for the client-side validation;
In this last case, the available properties are:

  • close_tips, boolean, TRUE or FALSE
    Specifies whether the tips with error messages should have a "close" button or not
    Default is TRUE.
  • disable_upload_validation, boolean, TRUE or FALSE
    Useful for disabling all client-side processing of file upload controls, so that custom plugins may be used for it (like, for instance, this one) Default is FALSE.
  • on_ready, JavaScript function to be executed when the form is loaded. Useful for getting a reference to the Zebra_Form object after everything is loaded.
  1. $form->clientside_validation(array(
  2.     // where $form is a global variable and 'id' is the form's id
  3.     'on_ready''function() { $form = $("#id").data('Zebra_Form'); }',
  4. ));

  • scroll_to_error, boolean, TRUE or FALSE
    Specifies whether the browser window should be scrolled to the error message or not.
    Default is TRUE.
  • tips_position, string, left or right
    Specifies where the error message tip should be positioned relative to the control.
    Default is left.
  • validate_on_the_fly, boolean, TRUE or FALSE
    Specifies whether values should be validated as soon as the user leaves a field; if set to TRUE and the validation of the control fails, the error message will be shown right away
    Default is FALSE.
  • validate_all, boolean, TRUE or FALSE
    Specifies whether upon submitting the form, should all error messages be shown at once if there are any errors
    Default is FALSE.
Top

method client_side_validation()

void client_side_validation ( $properties )

Alias of clientside_validation() method.

Deprecated since 2.8.9

Parameters:
$properties
Top

method csrf()

void csrf ( [ string $csrf_storage_method = 'auto'] , [ integer $csrf_token_lifetime = 0] , [ array $csrf_cookie_config = array('path' => '/', 'domain' => '', 'secure' => false, 'httponly' => false)] )

Enables protection against Cross-site request forgery (CSRF) attacks.

Read more about specifics and a simple implementation on Chris Shiflett's website.

This method is automatically called by the library, so protection against CSRF attacks is enabled by default for all forms and the script will decide automatically on the method to use for storing the CSRF token: if a session is already started then the CSRF token will be stored in a session variable or, if a session is not started, the CSRF token will be stored in a session cookie (cookies that expire when the browser is closed) but, in this case, it offers a lower level of security.

If cookies are used for storage, you'll have to make sure that Zebra_Form is instantiated before any output from your script (this is a protocol restriction) including &lt;html> and &lt;head> tags as well as any whitespace! A workaround is to turn output buffering on in php.ini.

You are encouraged to start a PHP session before instantiating this class in order to maximize the level of security of your forms.

The CSRF token is automatically regenerated when the form is submitted regardless if the form validated or not. A notable exception is that the form doesn't validate but was submitted via AJAX the CSRF token will not be regenerated - useful if you submit forms by AJAX.

As an added benefit, protection against CSRF attacks prevents "double posts" by design.

You only need to call this method if you want to change CSRF related settings. If you do call this method then you should call it right after instantiating the class and *before* calling the form's validate() and render() methods!

  1. // recommended usage is:
  2.  
  3. // call session_start() somewhere in your code but before outputting anything to the browser
  4.  
  5. // include the Zebra_Form
  6. require 'path/to/Zebra_Form.php';
  7.  
  8. // instantiate the class
  9. // protection against CSRF attack will be automatically enabled
  10. // but will be less secure if a session is not started (as it will
  11. // rely on cookies)
  12. $form new Zebra_Form('my_form');
Tags:
since: 2.8.4
Parameters:
string $csrf_storage_method

(Optional) Sets whether the CSRF token should be stored in a cookie, in a session variable, or let the script to automatically decide and use sessions if available or a cookie otherwise.

Possible values are "auto", "cookie", "session" or boolean FALSE.

If value is "auto", the script will decide automatically on what to use: if a session is already started then the CSRF token will be stored in a session variable, or, if a session is not started, the CSRF token will be stored in a cookie with the parameters as specified by the csrf_cookie_config argument (read below).

If value is "cookie" the CSRF token will be stored in a cookie with the parameters as specified by the csrf_cookie_config argument (read below).

If value is "session" the CSRF token will be stored in a session variable and thus a session must be started before instantiating the library.

If value is boolean FALSE (not recommended), protection against CSRF attack will be disabled.

The stored value will be compared, upon for submission, with the value stored in the associated hidden field, and if the two values do not match the form will not validate.

Default is "auto".

integer $csrf_token_lifetime

(Optional) The number of seconds after which the CSRF token is to be considered as expired.

If set to "0" the tokens will expire at the end of the session (when the browser closes or session expires).

Note that if csrf_storage_method is set to "session" this value cannot be higher than the session's life time as, if idle, the session will time out regardless of this value!

Default is 0.

array $csrf_cookie_config

(Optional) An associative array containing the properties to be used when setting the cookie with the CSRF token (if csrf_storage_method is set to "cookie").

The properties that can be set are "path", "domain", "secure" and "httponly". where:

  • path - the path on the server in which the cookie will be available on. If set to "/", the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all subdirectories such as /foo/bar/ of domain.
    Default is "/"
  • domain - The domain that the cookie will be available on. To make the cookie available on all subdomains of example.com, domain should be set to to ".example.com". The . (dot) is not required but makes it compatible with more browsers. Setting it to "www.example.com" will make the cookie available only in the www subdomain.
  • secure - Indicates whether cookie information should only be transmitted over a HTTPS connection.
    Default is FALSE.
  • httponly - When set to TRUE the cookie will be made accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. It has been suggested that this setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers), but that claim is often disputed. Available only in PHP 5.2.0+
    Default is FALSE

Available only for PHP 5.2.0+ and will be ignored if not available.

Not all properties must be set - for the properties that are not set, the default values will be used instead.

Top

method doctype()

void doctype ( [ string $doctype = 'html'] )

By default, this class generates HTML 4.01 Strict markup.

Use this method if you want the generated HTML markup to validate as XHTML 1.0 Strict.

Parameters:
string $doctype

(Optional) The DOCTYPE of the generated HTML markup.

Possible (case-insensitive) values are HTML or XHTML

Default is HTML.

Top

method language()

void language ( string $language )

Sets the language to be used by some of the form's controls (the date control, the select control, etc.)

The default language is English.

Parameters:
string $language

The name of the language file to be used, from the "languages" folder.

Must be specified without extension ("german" for the german language not "german.php")!

Top

method render()

mixed render ( [ string $template = ''] , [ boolean $return = false] , [ array $variables = ''] )

Renders the form.

Tags:
return: Returns or displays the rendered form.
Parameters:
string $template

The output of the form can be generated automatically, can be given from a template file or can be generated programmatically by a callback function.

For the automatically generated template there are two options:

  • when $template is an empty string or is "*vertical", the script will automatically generate an output where the labels are above the controls and controls come one under another (vertical view)
  • when $template is "*horizontal", the script will automatically generate an output where the labels are positioned to the left of the controls while the controls come one under another (horizontal view)

When templates are user-defined, $template needs to be a string representing the path/to/the/template.php.

The template file itself must be a plain PHP file where all the controls added to the form (except for the hidden controls, which are handled automatically) will be available as variables with the names as described in the documentation for each of the controls. Also, error messages will be available as described at set_rule().

A special variable will also be available in the template file - a variable with the name of the form and being an associative array containing all the controls added to the form, as objects.

The template file must not contain the <form> and </form> tags, nor any of the <hidden> controls added to the form as these are generated automatically!

There is a third method of generating the output and that is programmatically, through a callback function. In this case $template needs to be the name of an existing function.

The function will be called with two arguments:

  • an associative array with the form's controls' ids and their respective generated HTML, ready for echo-ing (except for the hidden controls which will still be handled automatically);
note that this array will also contain variables assigned through the assign() method as well as any server-side error messages, as you would in a custom template (see set_rule() method and read until the second highlighted box, inclusive)

  • an associative array with all the controls added to the form, as objects

THE USER FUNCTION MUST RETURN THE GENERATED OUTPUT!

boolean $return

(Optional) If set to TRUE, the output will be returned instead of being printed to the screen.

Default is FALSE.

array $variables

(Optional) An associative array in the form of "variable_name" => "value" representing variable names and their associated values, to be made available in custom template files.

This represents a quicker alternative for assigning many variables at once instead of calling the assign() method for each variable.

Top

method reset()

void reset ( )

Resets the submitted values for all of the form's controls (also resets the POST/GET/FILES superglobals)

Top

method show_all_error_messages()

void show_all_error_messages ( [ boolean $value = false] )

Sets how error messages generated upon server-side validation are displayed in an error block.

Client-side validation is done on the "onsubmit" event of the form. See clientside_validation() for more information on client-side validation.

  1. //  create a new form
  2. $form new Zebra_Form('my_form');
  3.  
  4. //  display all error messages of error blocks
Parameters:
boolean $value

Setting this argument to TRUE will display all error messages of an error block, while setting it to FALSE will display one error message at a time.

Default is FALSE.

Top

method validate()

boolean validate ( )

This method performs the server-side validation of all the form's controls, making sure that all the values comply to the rules set for these controls through the set_rule() method.

Only by calling this method will the form's controls update their values. If this method is not called, all the controls will preserve their default values after submission even if these values were altered prior to submission.

This method must be called before the render() method or error messages will not be available.

After calling this method, if there are file controls on the form, you might want to check for the existence of the $file_upload property to see the details of uploaded files and take actions accordingly.

Client-side validation is done on the "onsubmit" event of the form. See clientside_validation() for more information on client-side validation.

Tags:
return: Returns TRUE if every rule was obeyed, FALSE if not.
Top

method validate_control()

boolean validate_control ( string $control )

This method performs the server-side validation of a control, making sure that the value complies to the rules set for the control through the set_rule() method.

Tags:
return: Returns TRUE if every rule was obeyed, FALSE if not.
Parameters:
string $control Unique name that identifies the control in the form.
Top