Internet magazine of a summer resident. DIY garden and vegetable garden

Crazy validation php. Validation and data cleaning using PHP. Occurrences and exclusions


In a previous article I promised to write a comparison of my own library with other available solutions, so today we will look at validation using Aura.Filter, Respect Validation, Sirius Validation and Valitron.


Let's imagine that we have a certain public service in development that requires users to register for full access to all functions. Thus, the registration form will contain the following fields:

  • name. Must contain exactly two words, where the first is the user's first name and the second is the last name.
  • login. If a value is passed, it must contain only Latin letters, hyphens and underscores.
  • email. Must contain a valid email address.
  • password. Must be set and be no more than 64 characters long.
  • agreed. A typical checkbox that a user must check to confirm their acceptance of the terms of service.
  • So, we have five fields that the user must fill out in order to register with our imaginary service. Let's imagine that we received completely invalid data as input:


    $data = [ "name" => "Albert", // Must be two words "login" => "@lbert", // "Forbidden" character @ "email" => "something wrong", / / There should be an e-mail "password" => Aura.Filter

    Validation using Aura.Filter starts with a filter factory. We need to create a so-called “subject filter”, since we will be validating an array, not an individual value.

    We define the rules use Aura\Filter\FilterFactory; $filter = (new FilterFactory)->newSubjectFilter(); $filter->validate("name") ->isNotBlank() ->is("two_words") ->setMessage("The name must be two words."); $filter->validate("login") ->isBlankOr("alnum") ->setMessage("If you specify a login, it must contain only Latin characters."); $filter->validate("email") ->isNotBlank() ->is("email") ->setMessage("Please enter a valid email address."); $filter->validate("password") ->isNotBlank() ->is("strlenMax", 64) ->setMessage("Please write your password."); $filter->validate("agreed") ->is("callback", function($subject, $field) ( return $subject->($field) === true; ))->setMessage("You need agree to the terms of service.");

    As you can see, the description of the rules is quite simple. Aura.Filter provides a whole set of useful rules out of the box and some of them were used in the example above:

  • isNotBlank method. Specifies that the field cannot have a null value.
  • alnum. This rule only allows Latin letters.
  • email. And it’s so clear :)
  • strlenMax. Specifies that the field cannot exceed the length specified by the second argument of the is method.
  • callback. This type of rule is similar to closures from Kontrolio. It allows you to define a rule in the form of a closure. To this closure, Aura.Filter passes the “subject”, our array of data from the form, and a field, in this case agreed .
  • You probably noticed that I didn't specify the two_words rule. Naturally, there is no such rule in Aura.Filter, so we need to create one. As the documentation says, this is done using a separate class for the rule:


    /** * Rule that validates the username. * The username consists of two words: first and last name, separated by one space. */ class UserNameRule ( /** * Validates the username. * * @param object|array $subject * @param string $field * @param int $max * * @return bool */ public function __invoke($subject, $field , $max = null) ( $value = $subject->($field); if (! is_scalar($value)) ( return false; ) return (bool) preg_match("/^+\s+$/u", $value);

    The second step is to let the filter factory know about our new rule. It’s done by passing the first argument as an array of rules to the filter factory:


    The next step is to notify Aura.Filter that we have created a new rule and want to use it. This is done by passing an array of rules to the first argument of the factory:


    use Aura\Filter\FilterFactory; $rules = [ "two_words" => function() ( return new UserNameRule; ) ]; $filter = (new FilterFactory($rules))->newSubjectFilter();

    Now our two_words rule can be used in the same way as any other standard rule.

    Feedback

    As you remember, the incoming data that we validate is completely invalid, because each field contains an incorrect value or does not contain it at all. Therefore, it is assumed that as a result of validation we will receive errors and corresponding messages about them.


    We validate with Aura.Filter as follows:


    $valid = $filter->apply($data); if (! $valid) ( $failures = $filter->getFailures(); $messages = $failures->getMessages(); )

    IN $messages an array is being written, so to display messages we need two nested foreach:


    Respect Validation

    The second library I used in the comparison is a relatively popular solution called Respect Validation. Since people trust her, I think there is something to see there.


    For the purity of the experiment, when comparing libraries, we will use the same data set defined at the beginning:


    use Respect\Validation\Validator as v; $data = [ "name" => "Albert", // Must be two words "login" => "@lbert", // "Forbidden" character @ "email" => "something wrong", / / There should be an e-mail here "password" => "" // The password is not specified at all // "agreed" is not in the array because the user did not check the box ]; Defining the rules

    As with Aura.Filter, we need our own validation rule for the username, so let's start there:


    namespace MyNamespace; use Respect\Validation\Rules\AbstractRule; class UserNameRule extends AbstractRule ( public function validate($input) ( return (bool) preg_match("/^+\s+$/u", $input); ) )

    The external rules API is almost identical to Aura.Filter, only the validate() method is used instead of the __invoke() magic. It seemed to me, this API, simpler and more understandable. Well, it’s closer to Kontrolio :)


    I did not find any mention of this in the documentation, however, in addition to the rule itself, you need to create your own exception type for it. The name of the exception class must consist of the name of the rule class and a postfix Exception.


    use Respect\Validation\Exceptions\NestedValidationException; class UserNameRuleException extends NestedValidationException ( // )

    Well, finally we can validate our data. First, we pass our new rule to the validator so that he knows about it and we can use it in the future. In Respect Validation, this is done by calling the with() method, passing the namespace in which the non-standard rules are located.


    v::with("MyNamespace\\");

    Now all non-standard rules located in the namespace MyNamespace, will be “recognized” by the validator. The next step is to describe the necessary rules and perform validation.


    v::attribute("name", v::userNameRule()) ->attribute("login", v::alnum("-_")) ->attribute("email", v::email()) ->attribute("password", v::notEmpty()->stringType()->length(null, 64)) ->attribute("agreed", v::trueVal()) ->assert((object) $data);

    Notice how we apply our rule to the attribute name. Here the name of the rule class has been transformed into the name of the validator method. The remaining rules are, in general, intuitive.


    It’s worth mentioning separately why we provide the array $data to the object. The fact is that Respect Validation accepts objects, not arrays, as input. This should be taken into account when developing using this library.

    Feedback

    Unlike Aura.Filter, the Respect validator throws an exception when validation fails. And this exception contains validation error messages. Therefore, the example that was just shown should be written as follows:


    try ( v::with("RespectValidationExample\\"); v::attribute("name", v::userNameRule()) ->attribute("login", v::alnum("-_")) - >attribute("email", v::email()) ->attribute("password", v::notEmpty()->stringType()->length(null, 64)) ->attribute("agreed", v::trueVal()) ->assert((object) $data ) catch (NestedValidationException $ex) ( $messages = $ex->getMessages(); )

    Using getMessages() we will get a flat array of all messages that the validator collected during the validation process. By dumping the array, we get something like this:


    array(5) ( => string(29) “Data validation failed for %s” => string(60) “login must contain only letters (a-z), digits (0–9) and “-_”” => string (25) “email must be valid email” => string(26) “password must not be empty” => string(32) “Attribute agreed must be present” )

    You can change the messages to your own. Perhaps I somehow misunderstood this library, but this process did not seem so obvious to me: you need to use the findMessages() method on a handled exception, in which you define messages not for attributes, but for rules.


    $ex->findMessages([ "userNameRule" => "The username must consist of two words.", "alnum" => "We don't like your login.", "email" => "You obviously don't want to give us your e-mail.", "notEmpty" => "Well, where is your password?", "agreed" => "It's a pity that you disagree." ]);

    I don't know what's wrong, but there are a couple of things I still don't understand. This is what we get by defining the rules in the above way:


    array(5) ( => string(40) “The username must be two words.” => string(31) “We don’t like your login.” => string(25) “email must be valid email” => string(5) “Well, where is your password?” => string(9) “It’s a pity that you don’t agree.”

    As you can see, the message for the email field was not applied, the standard one remained. But the message at index 4 is the opposite! And this despite the fact that I did not use the name of the rule, but the name of the field. Whereas if I had used the rule name (trueVal), my message would have gotten lost somewhere. Comments from experienced users of this library are very welcome.

    Sirius Validation

    Ok, let's move on to the next library and see how it handles similar tasks.

    Defining the rules

    Once again we need to define a rule for the username. We'll write it something like this:


    class UserNameRule extends AbstractRule ( // Error Messages const MESSAGE = "The username must be two words."; const LABELED_MESSAGE = "(label) must be two words."; public function validate($value, $valueIdentifier = null ) ( return (bool) preg_match("/^+\s+$/u", $value); ) )

    Please note the difference in approaches compared to the libraries already discussed. We define two kinds of messages in constants rather than using properties, methods or rule arguments.


    Now let's describe the validation logic:


    $validator = new Validator; $validator ->add("name", "required | MyApp\Validation\Rule\UserNameRule") ->add("login", "required | alphanumhyphen", null, "Login can only contain Latin letters, dashes and underscores. ") ->add("email", "required | email", null, "Please enter a correct e-mail.") ->add("password", "required | maxlength(64)", null, "Your password, sir.") ->add("agree", "required | equal(true)", null, "Why didn't you agree?");

    As you can see, the set of rules is very simple and readable. For description, we use names separated by horizontal bars. This approach is similar to that used in Laravel and Kontrolio.


    The fourth argument to the add() method describes the validation error message that Sirius will use if the validation fails. Why didn't we add a message for our new rule? UserNameRule?


    $validator->add("name", "required | MyApp\Validation\Rule\UserNameRule")

    This is because the messages are already described in the class constants:


    class UserNameRule extends AbstractRule ( // Error messages const MESSAGE = "The username must be two words."; ...

    Another option is to use the addMessage() method of the validator itself:


    $validator->addMessage("email", "Please enter a valid e-mail.");

    Please note that custom rules are identified by the full name of their class, while in Kontrolio you can specify an alias/alias.

    Feedback

    To perform validation, we call the validator method validate() , passing data to it:


    $data = [ "name" => "Albert", // Must be two words "login" => "@lbert", // "Forbidden" character @ "email" => "something wrong", / / There should be an e-mail here "password" => "" // The password is not specified at all // "agreed" is not in the array because the user did not check the box ]; $validator->validate($data);

    Unlike Respect, Sirius will not throw an exception, but will simply return false. Validation error messages can be obtained through the getMessages() validator method. It returns errors grouped by attributes, so we need two foreach loops to go through the errors:


    foreach ($validator->getMessages() as $attribute => $messages) ( foreach ($messages as $message) ( echo $message->getTemplate() . "\n"; ) )

    Here $message is a class object Sirius\Validation\ErrorMessage, which has a getTemplate() method that returns the very message we need.

    ValitronDefining the rules

    The first difference: to add a new rule, you do not need to create a separate class. You can simply use a closure that returns a boolean result.


    To add custom rules, Valitron has a static method addRule(), in which the first two arguments are required, and the third is optional. I liked this method, since it shows the rule identifier, logic and error message in one place.


    use Valitron\Validator; Validator::addRule("two_words", function($field, $value) ( ​​return (bool) preg_match("/^+\s+$/u", $value); ), "The username must consist of exactly two words ");

    The second difference is how the rules are applied to attributes. In all previous cases, we saw that an attribute is, as it were, a primary thing.


    Valitron took a different route and put validation rules first. By describing rules, you seem to be applying attributes to these rules, and not vice versa.


    $validator = new Validator($data); $validator ->rule("two_words", "name")->label("") ->rule("required", [ "name", "login", "email", "password", "agreed" ] ) ->rule("slug", "login") ->rule("email", "email") ->rule("accepted", "agreed");

    As can be seen from the example, in the rule() method we first write the name of the rule, and only then indicate the attributes that must correspond to this rule. A more explicit example is the required rule, which shows how attributes "belong" to that rule.


    Valitron (like other solutions that we have reviewed) provides standard error messages. If you just use them, you will see that each message begins with the name of the corresponding attribute.


    Valitron substitutes attribute names into the message text even when non-standard error messages are used. That's why we used the label() method with an empty string to remove the attribute name.


    $validator->rule("two_words", "name")->label("") Feedback

    Specifically regarding validation, the Valitron library API is practically no different from what we have already seen in the article. To perform validation we call the validator method validate() :


    $validator->validate();

    Validation error messages can be retrieved using the getErrors() method:


    $validator->errors();

    Messages here are grouped by attributes in the same way as in Sirius Validation, except that there is no separate class for the message, and we get a regular multi-dimensional array.


    foreach ($validator->errors() as $attribute => $messages) ( foreach ($messages as $message) ( echo $message . "\n"; ) ) Kontrolio

    And finally, the last library for today is my own development called Kontrolio.

    Defining the rules

    Again, for the fifth time, we will create a validation rule for the username. Everything is relatively simple and standard:


    namespace MyProject\Validation\Rules; use Kontrolio\Rules\AbstractRule; class TwoWords extends Kontrolio\Rules\AbstractRule ( public function isValid($input = null) ( return (bool) preg_match("/^+\s+$/u", $input); ) )

    Now we create a factory and register a rule with it using the extend() method:


    namespace MyProject; use Kontrolio\Factory; use MyProject\Validation\Rules\TwoWords; $factory = Kontrolio\Factory::getInstance()->extend();

    After registering the rule, we can use it, including by name - two_words. Let's create a validator:


    $data = [ "name" => "Albert", // Must be two words "login" => "@lbert", // "Forbidden" character @ "email" => "something wrong", / / There should be an e-mail here "password" => "" // The password is not specified at all // "agreed" is not in the array because the user did not check the box ]; $rules = [ "name" => "two_words", "login" => "sometimes|alphadash", "email" => "email", "password" => "length:1.64", "agreed" = > "accepted" ]; $messages = [ "name" => "The username must consist of two words.", "login" => "We don't like your login.", "email" => "You obviously don't want to give us your email .", "password" => "Well, where is your password?", "agreed" => "It's a pity that you don't agree." ]; $validator = $factory->make($data, $rules, $messages);

    We described the rules using a syntax similar to that used in Laravel, although we could have used a more verbose version:


    $rules = [ "name" => new TwoWords, "login" => , "email" => new Email, "password" => new Length(1, 64), "agreed" => new Accepted ]; Feedback

    Validation is started using the same validate() method:


    $validator->validate();

    Now we can get error messages using one of the getErrors() or getErrorsList() methods. The first method allows for more complex error output, while the second returns a flat array. Using getErrors() we can output messages something like this:



    And with getErrorsList() you can make a simpler list of messages:


    Bottom line

    In this article I showed examples of using the following libraries:

  • Aura.Filter
  • Respect Validation
  • Sirius Validation
  • Valitron
  • control
  • A “real world example” may seem too simple. I have to agree, since, indeed, some library capabilities were left out of the article. In principle, if you are interested, you can study their features yourself.


    Each of the libraries offers its own features and has its dark sides, so I think it’s a matter of taste and challenge to choose the one.


    Thanks for reading. Make the right choice.

    Tags: Add tags

    It is very essential to have the input to your form validated before taking the form submission data for further processing. When there are many fields in the form, the PHP validation script becomes too complex. Moreover, since you are doing the same or similar validation for most of the forms that you make, just too much of duplicate effort is spent on form validations.

    About this generic PHP form validation script

    This generic PHP form validator script makes it very easy to add validations to your form.

    We create and associate a set of “validation descriptors” with each element in the form. The “validation descriptor” is a string specifying the type of validation to be performed. For example, “req” means required, “alpha” means allow only alphabetic characters and so on.

    Each field in the form can have zero, one or more validations. For example, the input should not be empty, should be less than 25 chars, should be alpha-numeric, etc

    You can associate a set of validation descriptors for each input field in the form.

    Download the PHP form validation script

    You can download the PHP form validation script below:
    The zip file contains the form validation script formvalidator.php, documentation and usage samples.

    Using the PHP form validation script
  • Include formvalidator.php in your form processing script
  • require_once "formvalidator.php"
  • Create a FormValidator object and add the form validation descriptors.
  • $validator = new FormValidator(); $validator->addValidation("Name","req","Please fill in Name"); $validator->addValidation("Email","email", "The input for Email should be a valid email value"); $validator->addValidation("Email","req","Please fill in Email");

    The first argument is the name of the input field in the form. The second argument is the validation descriptor that tells the type of the validation required. The third argument is the error message to be displayed if the validation fails.

  • Validate the form by calling ValidateForm() function
  • if(!$validator->ValidateForm()) ( echo "Validation Errors:"; $error_hash = $validator->GetErrors(); foreach($error_hash as $inpname => $inp_err) ( echo "

    $inpname: $inp_err

    \n"; ) ) Example

    The example below will make the idea clearer

    Name: Email:

    Adding Custom Validation

    If you want to add a custom validation, which is not provided by the validation descriptors, you can do so. Here are the steps:

  • Create a class for the custom validation and override the DoValidate() function
  • class MyValidator extends CustomValidator ( function DoValidate(&$formars,&$error_hash) ( if(stristr($formars["Comments"],"http://")) ( $error_hash["Comments"]="No URLs allowed in comments"; return false; ) return true; ) )

  • Add the custom validation object
  • $validator = new FormValidator(); $validator->addValidation("Name","req","Please fill in Name"); $validator->addValidation("Email","email", "The input for Email should be a valid email value"); $validator->addValidation("Email","req","Please fill in Email"); $custom_validator = new MyValidator(); $validator->AddCustomValidator($custom_validator);

    The custom validation function will be called automatically after other validations.

    Table of Validation Descriptors

    Here is the list of all validation descriptors:

    Validation DescriptorUsage
    reqThe field should not be empty
    maxlen=???checks the length entered data to the maximum. For example, if the maximum size permitted is 25, give the validation descriptor as “maxlen=25”
    minlen=???checks the length of the entered string to the required minimum. example “minlen=5”
    alnumCheck the data if it contains any other characters other than alphabetic or numeric characters
    alnum_sAllows only alphabetic, numeric and space characters
    numCheck numeric data
    alphaCheck alphabetic data.
    alpha_sCheck alphabetic data and allow spaces.
    emailThe field is an email field and verify the validity of the data.
    lt=???
    lessthan=???
    Verify the data to be less than the value passed. Valid only for numeric fields.
    example: if the value should be less than 1000 give validation description as “lt=1000”
    gt=???
    greaterthan=???
    Verify the data to be greater than the value passed. Valid only for numeric fields.
    example: if the value should be greater than 10 give validation description as “gt=10”
    regexp=???Check with a regular expression the value should match the regular expression.
    example: “regexp=^(1.20)$” allow up to 20 alphabetic characters.
    dontselect=??This validation descriptor is for select input items (lists) Normally, the select list boxes will have one item saying ‘Select One’. The user should select an option other than this option. If the value of this option is ‘Select One’, the validation description should be “dontselect=Select One”
    dontselectchkThis validation descriptor is for check boxes. The user should not select the check given box. Provide the value of the check box instead of ??
    For example, dontselectchk=on
    shouldselchkThis validation descriptor is for check boxes. The user should select the given check box. Provide the value of the check box instead of ??
    For example, shouldselchk=on
    dontselectradioThis validation descriptor is for radio buttons. The user should not select the given radio button. Provide the value of the radio button instead of ??
    For example, dontselectradio=NO
    selectradioThis validation descriptor is for radio buttons. The user should select the given radio button. Provide the value of the radio button instead of ??
    For example, selectradio=yes
    selmin=??Select atleast n number of check boxes from a check box group.
    For example: selmin=3
    seloneMakes a radio group mandatory. The user should select atleast one item from the radio group.
    eqelmnt=???compare two elements in the form and make sure the values ​​are the same For example, ‘password’ and ‘confirm password’. Replace the ??? with the name of the other input element.
    For example: eqelmnt=confirm_pwd

    Reg.ru: domains and hosting

    The largest registrar and hosting provider in Russia.

    More than 2 million domain names in service.

    Promotion, domain mail, business solutions.

    More than 700 thousand customers around the world have already made their choice.

    *Mouse over to pause scrolling.

    Back forward

    Validation and data cleaning using PHP

    Data security is a very important point that is often underestimated by both developers and clients. Starting with PHP 5.2.0, data cleaning and validation (checking for compliance with certain criteria) has become easier with the introduction of data filtering. Today we'll look at filtering techniques, how to use filters, and create some custom functions.

    Introduction

    I've always felt that writing code in PHP is easy, and it's even easier to write bad code in PHP. The widespread use of PHP in the field of web development has been facilitated by many open-source projects such as WordPress, Drupal, Magento. In addition, these are web applications like Facebook, etc. With such widespread use of PHP (dynamic websites, blogging platforms, content management systems, use in e-commerce applications, etc.), the likelihood of encountering dirty information and insecure systems is very high. This tutorial will show some methods for cleaning and validating data using PHP. We'll focus on several input types and how to use PHP filters and custom functions.

    Why clean and check?

    In this guide, we will focus on information that comes directly from users, as well as from other external sources. This means that we have no control over the information we receive. All we can do is control what will be done with this information received. Almost all types of threats come from information transmitted by users or other third parties.

    Among the main ones:

    - XSS (Cross-Site Scripting)

    This is a method of code injection where a script is injected into a page of the attacked website from a completely different site on a different server. This vulnerability is considered one of the most common on the network.

    - SQL injection

    The next popular vulnerability is another form of code injection, which allows for various types of malicious behavior, including unauthorized access to information, changing database information, or otherwise disrupting the normal functioning of a web application. This attack is carried out by injecting arbitrary SQL code into the request, designed to interact with the database.

    - CSRF/XSRF (Cross-Site Request Forgery)

    This vulnerability is less common than the previous ones. Typically, this kind of vulnerabilities arise when working with sessions and cookies, and less often when poorly verified and cleaned data. CSRF can be used to allow a site to make any requests without the user's knowledge. One of the known ways to implement this attack is to use a malformed attribute src at the picture, which leads to the execution of some script, and not to the display of the picture.

    - Incorrect information

    Incorrect information in itself is not a “vulnerability.” However, such information in many cases leads to a number of problems for both the site owner and the database administrator. Often, information that is incorrect in structure leads to disruptions in operation, especially if the site is implemented at an amateur level, not according to standards, as well as to failures in the operation of automated systems that expect clearly structured data in a certain format for processing.


    Translation of the dialogue to the picture:

    Hello, it's your son's school who are bothering you. We're having trouble with computers here.

    Oh God, did he break something?

    Your son's real name is Robert"); DROP TABLE students;?

    Oh yes we call him Little Bobby Tables

    You understand, we have lost all records for this year's students. I hope you are satisfied.

    And I hope you will learn to check the information entered into the database.

    For our purposes, we'll only focus on using server-side techniques to improve information security, so let's look at how the terms "sanitization" and "validation" are defined as they apply to PHP. Let's take a look at the PHP manual:

    "Validation is used to check whether the information being verified meets certain requirements. For example, using FILTER_VALIDATE_EMAIL we determine whether the information is a valid (ie, structurally correct) e-mail address, but do not change this data.

    Cleaning implies a possible change in the information being checked, for example, removing unwanted characters. For example, when using FILTER_SANITIZE_EMAIL, characters that should not be contained in the e-mail address will be removed. Those. In this case, there is no verification of the correctness of the address (i.e., validation), but obviously inappropriate characters are removed - nothing more."

    Essentially, if you think of your site as a nightclub that everyone wants to go to, validation is the job of checking to see if a guest is on the guest list, sanitization is the bouncer that keeps unwanted elements out of the club. Like that.

    What filters do I have?

    All PHP installations cannot be identical. Even though filters were introduced in PHP 5.2.0, not all installations have the same set of filters. In most cases, all the filters we'll talk about will already be included with PHP installed on your server, but to help you know a little more about filters, we'll look at what's available on your server specifically. The source code file is attached getfilters.php, which, once installed and running on the server, will display a list of all your filters (like the information filters available through the function filter_var, and streaming, available through stream_filter_append)

    Echo "Data Filters\n

    \n \n"; echo " \n"; echo " \n"; foreach(filter_list() as $id =>$filter) ( echo " \n"; ) echo "
    Filter IDFilter Name
    $filter".filter_id($filter)."
    \n";

    First we get an array containing a list of all available filters using the function filter_list, after which we loop through the array, displaying the filter name and its ID.

    How do I use the filter?

    PHP filters for validation and purification are activated by passing a function filter_var at least two parameters. As an example, let's apply a clearing filter to an integer:

    $value = "123abc456def"; echo filter_var($value, FILTER_SANITIZE_NUMBER_INT); !}

    In this example we have a variable value, which we pass to the function filter_var from the PHP Filters Extension using the FILTER_SANITIZE_NUMBER_INT filter. As a result we will get:

    The cleanup filter for integers removes all non-integer characters, giving us a "clean" integer. In the sources you can try different inputs and a number of common filters will be applied to them. The archive includes various strings that you can use as test material yourself.

    What do the different filters do?

    The list below is incomplete, but it contains most of the filters that come with a standard PHP 5.2.0+ installation.

    FILTER_VALIDATE_BOOLEAN: Checks whether the passed information is a boolean value TRUE or FALSE. If the passed value is not a Boolean value, then FALSE is returned. The script below will print TRUE for the variable example value1 value02:

    $value01 = TRUE; if(filter_var($value01,FILTER_VALIDATE_BOOLEAN)) ( echo "TRUE"; ) else ( echo "FALSE"; ) echo "

    " $value02 = FALSE; if(filter_var($value02,FILTER_VALIDATE_BOOLEAN)) ( echo "TRUE"; ) else ( echo "FALSE"; )

    FILTER_VALIDATE_EMAIL: Checks whether the information passed is a valid e-mail address in terms of structure. It does not check whether this address actually exists, but only the validity of the address, i.e. the correctness of its structure. The script below will print TRUE for the variable example value01 and FALSE for the variable example value02(since the required part with the @ sign is missing):

    $value01 = " [email protected]"; if(filter_var($value01,FILTER_VALIDATE_EMAIL)) ( echo "TRUE"; ) else ( echo "FALSE"; ) echo "

    " $value02 = "nettuts"; if(filter_var($value02,FILTER_VALIDATE_EMAIL)) ( echo "TRUE"; ) else ( echo "FALSE"; )

    FILTER_VALIDATE_FLOAT: Checks whether the passed value is a floating point number. The script below will print TRUE for the variable example value01 and FALSE for the variable example value02(since split "," is not allowed in floating point numbers):

    $value01 = "1.234"; if(filter_var($value01,FILTER_VALIDATE_FLOAT)) ( echo "TRUE"; ) else ( echo "FALSE"; ) echo "

    " $value02 = "1.234"; if(filter_var($value02,FILTER_VALIDATE_FLOAT)) ( echo "TRUE"; ) else ( echo "FALSE"; )

    FILTER_VALIDATE_INT: Checks whether the passed value is an integer. The script below will print TRUE for the variable example value01 and FALSE for the variable example value02(decimal numbers are not integers):

    $value01 = "123456"; if(filter_var($value01,FILTER_VALIDATE_INT)) ( echo "TRUE"; ) else ( echo "FALSE"; ) echo "

    " $value02 = "123.456"; if(filter_var($value02,FILTER_VALIDATE_INT)) ( echo "TRUE"; ) else ( echo "FALSE"; )

    FILTER_VALIDATE_IP: Checks if the value passed is a valid IP address. It does not check whether there is a response from this address, but only that the transferred value is, by its structure, an IP address. The script below will print TRUE for the variable example value01 and FALSE for the variable example value02:

    $value01 = "192.168.0.1"; if(filter_var($value01,FILTER_VALIDATE_IP)) ( echo "TRUE"; ) else ( echo "FALSE"; ) echo "

    " $value02 = "1.2.3.4.5.6.7.8.9"; if(filter_var($value02,FILTER_VALIDATE_IP)) ( echo "TRUE"; ) else ( echo "FALSE"; )

    FILTER_VALIDATE_URL: Checks if the value passed is a valid URL. It doesn't check, it doesn't check that the resource is accessible, only that the URL structure is followed. The script below will print TRUE for the variable example value01 and FALSE for the variable example value02:

    $value01 = "http://net.tutsplus.com"; if(filter_var($value01,FILTER_VALIDATE_URL)) ( echo "TRUE"; ) else ( echo "FALSE"; ) echo "

    " $value02 = "nettuts"; if(filter_var($value02,FILTER_VALIDATE_URL)) ( echo "TRUE"; ) else ( echo "FALSE"; )

    FILTER_SANITIZE_STRING: By default, this filter removes any invalid or unauthorized information in a string. For example, it will remove any HTML tags like or from the input string:

    $value = "alert("TROUBLE HERE");"; echo filter_var($value, FILTER_SANITIZE_STRING); !}

    This script will remove the tags and return the following:

    Alert("TROUBLE HERE");

    FILTER_SANITIZE_ENCODED: Many programmers use the function urlencode(). This filter essentially performs the same functions. For example, the following example will encode any special characters and spaces in the input string:

    $value = "alert("TROUBLE HERE");"; echo filter_var($value, FILTER_SANITIZE_ENCODED); !}

    The script will encode punctuation, spaces, parentheses and return the following:

    %3Cscript%3Ealert%28%27TROUBLE%20HERE%27%29%3B%3C%2Fscript%3E

    FILTER_SANITIZE_SPECIAL_CHARS: This filter defaults to HTML encoding of special characters such as quotes, ampersands, and parentheses. Since the demo page can't show this explicitly (since the HTML-encoded special characters will be interpreted by the browser and displayed), you can see it if you look at the source code:

    $value = "alert("TROUBLE HERE");"; echo filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS); !}

    The special characters will be converted into their HTML entities:

    FILTER_SANITIZE_EMAIL: This filter does exactly what everyone thought it would do. It removes characters from the address that should not be in the address (round and square brackets, colons, etc.) Let's say you accidentally added brackets around a letter to your address (don't ask me how, use your imagination :) )

    $value = "t(e) [email protected]"; echo filter_var($value, FILTER_SANITIZE_EMAIL);

    The brackets will be removed and you will receive your clean and beautiful e-mail:

    [email protected]

    This is an excellent filter that can be used in email forms, especially when paired with FILTER_VALIDATE_EMAIL, which will reduce user errors and prevent XSS attacks.

    FILTER_SANITIZE_URL: This filter is similar to the previous one. It removes any characters that are not allowed in the URL. For example, let's say there was a "®" sign in the address by chance. Again, how he got there is a complete mystery.

    $value = "http://net.tuts®plus.com"; echo filter_var($value, FILTER_SANITIZE_URL); !}

    This way we will remove the unnecessary "®" sign and get a normal address:

    http://net.tutsplus.com

    FILTER_SANITIZE_NUMBER_INT: This filter is similar to FILTER_VALIDATE_INT, but instead of simply checking whether a number is an integer, it also removes anything that is not an integer. An excellent thing, especially against annoying spam bots and deceivers who try to enter some nonsense into the field:

    $value01 = "123abc456def"; echo filter_var($value01, FILTER_SANITIZE_NUMBER_INT); echo "
    "; $value02 = "1.2.3.4.5.6.7.8.9"; echo filter_var($value02, FILTER_SANITIZE_NUMBER_INT);

    123456 123456789

    FILTER_SANITIZE_NUMBER_FLOAT: Similar to FILTER_VALIDATE_INT. It also allows you to achieve a similar effect:

    $value01 = "123abc456def"; echo filter_var($value01, FILTER_SANITIZE_NUMBER_FLOAT); echo "
    "; $value02 = "1.2.3.4.5.6.7.8.9"; echo filter_var($value02, FILTER_SANITIZE_NUMBER_FLOAT);

    Both sets of characters are converted and the output is the following:

    123456 123456789

    $value = "1.23"; echo filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT);

    The point will be removed and the value returned:

    One of the main reasons that the FILTER_SANITIZE_NUMBER_FLOAT and FILTER_SANITIZE_INT filters are separated is the ability to use the special flag FILTER_FLAG_ALLOW_FRACTION, which comes as the third parameter passed to the function filter_var:

    $value = "1.23"; echo filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

    Options, flags and control arrays - Mein Gott!

    The flag used in the previous example is just one way to gain more granular control over the types of data that will be cleaned, delimiter definitions, how arrays are processed by filters, etc. You can learn more about the flags and functions used in connection with the use of filters in the PHP manual, in the part dedicated to Filters - php.net/manual/en/book.filter.php.

    Other methods for clearing information using PHP

    We'll now look at a few key data scrubbing techniques to prevent an attack on your application. They are especially relevant for those applications that still run on PHP4, as they appeared with its release.

    htmlspecialchars: This PHP function converts 5 special characters into corresponding HTML entities.

    The following are subject to transformation:

    & (ampersand)
    " (double quotes) when the ENT_NOQUOTES flag is not set
    ’ (single quotes) only when the ENT_QUOTES flag is set
    < (меньше, чем)
    > (more than)

    This function is used in the same way as any other in PHP:

    Echo htmlspecialchars("$string");

    htmlentities: Similar to a function htmlspecialchars this function converts special characters to their HTML entities. The only difference is that in this case all special characters that can be converted are converted. This is a fairly common method for obfuscating e-mail addresses from spam bots, since not all of them are configured to read html entities:

    Echo htmlentities("$string");

    mysql_real_escape_string: This is a MySQL feature that helps protect against SQL injection attacks. It is considered good practice (and in fact a necessity) to pass all information passed to the SQL query through this function. It escapes all dangerous special characters that can cause problems and cause little Bobby Tables will destroy another table in the school database.

    $query = "SELECT * FROM table WHERE value=".mysql_real_escape_string("$string")." LIMIT 1,1"; $runQuery = mysql_query($query); !}

    Custom Functions

    For many people, the built-in features and filters may not be enough. Often more stringent and narrower validation or purification may be required. To achieve the desired results, many people write functions for data validation themselves. An example is the option of searching a database for values ​​of a certain type, like:

    Function checkZipCode($value) ( ​​$zipcheck = "SELECT COUNT(*) FROM `database`.`zipcodes` WHERE value="".filter_var(mysql_real_escape_string($value),FILTER_SANITIZE_NUMBER_INT)."""; $count = mysql_query( $zipcheck); if($count==1) ( return TRUE; ) else ( return FALSE; ) )

    Other user functions may not be directly connected to the database, but prepare information before inserting it into the database:

    Function cleanString($string) ( $detagged = strip_tags($string); if(get_magic_quotes_gpc()) ( $stripped = stripslashes($detagged); $escaped = mysql_real_escape_string($stripped); ) else ( $escaped = mysql_real_escape_string($ detagged); return $escaped;

    The possibilities are almost endless, especially when using regular expressions. However, for most cases, the use of filters can already solve the necessary problems.

    Did you like the material and want to thank me?
    Just share with your friends and colleagues!


    We will talk about the validation of POST or GET data, although in principle this can also be applied to data received by other methods, such as cookies. As you develop any web application, you need to write an interface for interacting with users and naturally create various forms for users to send data to the server. for example, these could be comments. I think it’s clear and obvious to everyone that the received data needs to be checked to see if it corresponds to the type, size, and specified range. First of all, this is required for the security of the system, website or database, because... Incorrectly transmitted data or a deliberately poorly formed request can open access to an attacker.

    Secondly, unverified data, if incorrect, can cause unstable operation of the script, the system or the entire server. Therefore, all data needs to be checked and double-checked; perhaps someone will say that there is no need for excessive paranoia, but I believe that in this matter it simply cannot be excessive.

    Do not trust data received from users, under any pretext, under any circumstances. It happens that we are simply too lazy to write code that checks the received data once again, or we hope that the existing verification methods are enough, as a result of which we make concessions to ourselves.

    A little digression from the topic:
    Working on projects, developing and programming websites, scripts, and other systems takes up almost all of my free time (besides working time), in other words, I do this work for the maximum possible number of hours a day. From time to time there is a need to test something, for fun or just curiosity. As a result, sites made in haste, using homemade engines or CMS of ancient versions, become similar testing laboratory rats. Of course, all of the above suffers from crookedly written code, lack of data control and is simply teeming with various bugs. Actually, in most cases, in an hour of my experiments on such sites, I manage to find several serious vulnerabilities, and most of them lie in insufficient validation of the received data. Recently, this has often been found in scripts that process POST data received from JavaScript + Ajax.

    Apparently, the programmers who wrote these scripts using Ajax believe that since all requests occur in the background, without the user’s knowledge or simply without reloading the page, then the data need not be particularly checked.

    As a rule, quite a few of these scripts turn out to be so full of holes that without much effort they manage to make a larger hole and flood their shell. of course, solely for the purpose of experimentation and nothing more (the administration of such sites is always informed of existing vulnerabilities).

    I think the importance of validation is clear to everyone. For a long time, I wrote the same piece of code each time, then used my own data verification functions, many of which were very primitive and, as a rule, scattered in different parts of (included) files. Soon I began to get acquainted with the PHP frameworks Zend, CI, Kohana, each of which implemented its own class for validating data that I borrowed for my projects. In the end, I decided to tailor one of the CI classes to my needs, but it turned out that the author of one of the programming blogs had already taken care of this. Next, I share his works, namely the modified CodeIgniter library.

    Let's look at the following code:

    View code PHP

    require_once "validator.class.php" ; $validator = new Validator() ; $validator -> set_rules ("name" , "Your name" , array ("required" => , "alpha" => ) ) ; $validator -> set_rules ("email" , "Your email" , array ("required" => "Field %s is required" , "valid_email" => ) ) ; if ($validator -> run () ) ( echo "Validation was successful" ; ) else ( echo $validator -> get_string_errors () ; )

    As you can see from the example, in the first line we include the class file validator.calss.php to our script. Next, we create an instance of the class and save the object to a variable $validator.
    Then using the method $validator->set_rules($field, $label, $rules) set the fields for validation.

    This method takes 3 parameters:

  • $field- name of the validation field (the value of the name attribute in the tag)
  • $label- name of the validation field, will be inserted into error messages
  • $rules- an array of validation rules, in which the validation rule is used as the key, and the error message for this rule is used as the value
  • After all the fields for validation are set, we launch the validator using the method $validator->run(). If validation was successful, this method will return the value TRUE, otherwise, if there are any errors, it will return FALSE.

    There are three methods to receive error messages:

  • get_string_errors()- returns all error messages as a string
  • get_array_errors()— returns all messages as an array, where the field name is used as the key, and the error description for this field is used as the value.
  • form_error($field)- returns an error message for the field passed as the $field parameter
  • By default, error messages are wrapped in a tag . To set your design, use the method set_error_delimiters($prefix, $suffix). For example like this:

    Error messages will now appear as div with class "error"

    As you can see, everything is very simple.

    View code PHP

    $validator -> set_error_delimiters ( " " , " " ) ;

    To set validation rules, you can use the method set_rules($fields) pass a multidimensional associative array. Let's look at an example:

    View code PHP

    $rules = array ( array ( "field" => "name" , "label" => "Your name" , "rules" => array ( "required" => "Field %s is required" , "alpha" => "Field %s must contain only letters" ) , array ( "field" => "email" , "label" => "Your email" , "rules" => array ( "required" => "Field % s is required" , "valid_email" => "Field %s must contain a valid email address" ) ) ) ; $validator -> set_rules ($rules ) ;

    As you can see, I wrote down the same validation rules as in the first example, only in the form of a multidimensional associative array. You can use any of the methods that suit you best in a given situation.

    So, what validation rules does this class support?

    I brought to this class the most common validation rules that everyone encounters. Here is a complete list of these rules:

    requiredReturns FALSE if the field is empty
    integerReturns FALSE if the value is not an integer
    floatReturns FALSE if the value is not a numeric value
    valid_urlReturns FALSE if value is not a valid URL
    valid_emailReturns FALSE if value is not a valid email address
    valid_ipReturns FALSE if the IP address is not valid
    matchesReturns FALSE if the element does not match the value of another field element
    alphaReturns FALSE if the element contains more than just letters
    valid_captchaReturns FALSE if the value in the session field is not equal to the value of the form field
    valid_dateReturns FALSE if the element contains an invalid date

    Most of these rules use filters, which became available in PHP 5.

    If you wish, you can always expand the set of rules for validation by adding the necessary functions to the Validator class.

    To get the processed POST data value, use the following method:

    View code PHP

    Typically this method is called to clear the form upon successful processing of the form.

    Validation of data is a fundamentally important aspect of a CRUD application. You need to be sure that the data that the client is sending you is what you expect. This is not just for security reasons, protecting your data from misuse and intentional corruption, but also simply from unintentional mistakes in submitting data. Strings limited to a certain length, dates in a particular format and required fields are all common uses of data validation.

    The Editor PHP libraries provide two different validation methods:

    • Field based, where each individual value submitted is independently validated: Field->validator() .
    • Global validation, where the data submitted by the client-side can be validated as a whole: Editor->validator() .
    Legacy information (v1.6-)

    Please note that PHP validation in Editor 1.6 and older was a little different. The older form of validation will still work with the 1.7+ libraries and its documentation remains available , but for new projects use the validation style discussed here.

    Field validation is the one you will most commonly work with - for example checking that an e-mail address field actually contains an e-mail address, and Editor provides a number of ready to use validators for the most common data types as well as the ability to specify your own. Global validation can be useful when checking dependencies between fields and conflicts in the existing data set.

    Field validation

    The Editor PHP libraries provide a validator() method for the Field class and a number of pre-built validation methods in the Validate class. Each of these validation methods returns a function which is executed when required to validate submitted data.

    Consider the following example - the Validate::minNum() function is configured with a number and returns a function that can be used for the field validator.

    Field::inst("age") ->validator(Validate::minNum(16));

    Please see below for more detailed examples.

    Validation options

    Each validation method provided by the Validation class can optionally accept parameters to tell it how to validate data (for example the minLen method will accept an integer to indicate the minimum length of an acceptable string), but all optionally accept a ValidateOptions class instance. This class defines a number of options that are shared between all validation methods.

    The ValidateOptions class is constructed with ValidateOptions::inst() (or new ValidateOptions() in PHP 5.4+) similar to the other Editor classes. It has three methods that can be used to alter the validation behavior:

    • ->allowEmpty(boolean) : How to handle empty data (i.e. a zero length string):
      • true (default) - Allow the input for the field to be zero length
      • false - Disallow zero length inputs
    • ->message(string) : the error message to show if the validation fails. This is simply "Input not valid" by default, so you will likely want to customize this to suit your needs.
    • ->optional(boolean) : Require the field to be submitted or not. This option can be particularly useful in Editor as Editor will not set a value for fields which have not been submitted - giving the ability to submit just a partial list of options.
      • true (default) - The field does not need to be in the list of parameters sent by the client.
      • false - The field must be included in the data submitted by the client.
    Example - setting a custom error message Field::inst("stock_name") ->validator(Validate::minNum(10, new ValidateOptions::inst() ->message("Stock name must be at least 10 characters long") )); Multiple validators

    It can often be useful to use multiple validators together, for example to confirm that an input string is less than a certain number of characters and also that it is unique in the database. Multiple validators can be added to a field simply by calling the Field->validator() method multiple times. Rather than overwriting the previous validator it will in fact add them together. They are run in the sequence they were added, and all validators must pass for the data to be accepted as valid.

    As an example consider the following code which will check the min and max length of the data, and also that it is unique:

    Field::inst("stock_name") ->validator(Validate::minLen(10)) ->validator(Validate::maxLen(12)) ->validator(Validate::unique());

    Ready to use field validators

    The Validate class in the Editor PHP libraries has a number of methods which can be used to perform validation very quickly and easily. These are:

    Basic
    • none(ValidateOptions $cfg=null) - No validation is performed
    • basic(ValidateOptions $cfg=null) - Basic validation - only the validation provided by ValidateOptions is performed
    • required(ValidateOptions $cfg=null) - The field must be submitted and the data must not be zero length. Note that Editor has the option of not submitting all fields (for example when inline editing), so the notEmpty() validator is recommended over this one.
    • notEmpty(ValidateOptions $cfg=null) - The field needs not be submitted, but if it is, it cannot contain zero length data
    • boolean(ValidateOptions $cfg=null) - Check that boolean data was submitted (including 1, true on, yes, 0, false, off and no)
    Numbers
    • numeric(string $decimalChar=".", ValidateOptions $cfg=null) - Check that any input is numeric.
    • minNum(integer $min, string $decimalChar=".", ValidateOptions $cfg=null) - Numeric input is greater than or equal to the given number
    • maxNum(integer $max, string $decimalChar=".", ValidateOptions $cfg=null) - Numeric input is less than or equal to the given number
    • minMaxNum(integer $min, integer $max, string $decimalChar=".", ValidateOptions $cfg=null) - Numeric input is within the given range (inclusive)
    Strings
    • email(ValidateOptions $cfg=null) - Validate an input as an e-mail address.
    • ip(ValidateOptions $cfg=null) - Validate as an IP address.
    • minLen(integer $min, ValidateOptions $cfg=null) - Validate a string has a minimum length.
    • maxLen(integer $max, ValidateOptions $cfg=null) - Validate a string does not exceed a maximum length.
    • minMaxLen(integer $min, integer $max, ValidateOptions $cfg=null) - Validate a string has a given length in a range
    • noTags(ValidateOptions $cfg=null) - Don"t allow HTML tags
    • url(ValidateOptions $cfg=null) - Validate as an URL address.
    • values(array $values, ValidateOptions $cfg=null) - Allow only values ​​which have been specified in an array of options (the first parameter). This could be useful if you wish to have free-form input or event a select list, and want to confirm that the value submitted is within a given data set (see also the dbValues() method if valid values ​​are stored in a database) . Note that the values ​​given in the values ​​array are checked against the submitted data as case-sensitive data (i.e. `"A" != "a").
    • xss(ValidateOptions $cfg=null) - Check to see if the input could contain an XSS attack . This used the Field "s XSS formatting function to determine if the input string needs to be formatted or not.
    Date/time
    • dateFormat(string $format, ValidateOptions $cfg=null) - Check that a valid date input is given. The format is defined by PHP's date() method which is used for the parsing of date and time string.
    Database
    • dbValues(ValidateOptions $cfg=null, string $column=null, string $table=null, Database $db=null, array $valid=null) - Allow only a value that is present in a database column. This is specifically designed for use with joined tables (i.e. ensure that the reference row is present before using it), but it could potentially also be used in other situations where referential integrity is required.
    • unique(ValidateOptions $cfg=null, string $column=null, string $table=null, array $db=null) - Ensure that the data submitted is unique in the table"s column.
    One-to-many (Mjoin)

    Note that these methods are for use with the Mjoin->validator() method (Editor 1.9 and newer). Please see the Mjoin documentation for more details.

    • mjoinMinCount($minimum, ValidateOptions $cfg=null) - Require that at least the given number of options / values ​​are submitted for the one-to-many join.
    • mjoinMaxCount($maximum, ValidateOptions $cfg=null) - Require that this many or less options / values ​​are submitted for the one-to-many join.
    Custom field validators

    If the provided methods above don"t suit the kind of validation you are looking for, it is absolutely possible to provide custom validation methods. The validator() Field method will accept a function that returns either true or a string and accepts the following input parameters:

  • value - The value to be validated
  • data - The collection of data for the row in question
  • field -The host Field instance
  • host - Information about the host Editor instance
  • The return value should be true to indicate that the validate passed, or a string that contains an error message if the validation failed.

    The following simple example shows how a maxLen string check could be implemented with a custom validation method:

    Field::inst("last_name") ->validator(function ($val, $data, $field, $host) ( return strlen($val) > 50 ? "Name length must be 50 characters or less" : true; ));

    Field validation examples

    Use the Validation.minNum() method to validate an input as numeric and greater or equal to a given number (no validation options specified, so the defaults are used):

    // Simple non-empty field Field::inst("age") ->validator(Validate::minNum(16))

    As above, but with ValidateOptions used to set the error message:

    // Number range check with custom error message Field::inst("range") ->validator(Validate::minNum(16, ValidateOptions::inst() ->message("Minimum age is 16")));

    This time validating an e-mail address which cannot be empty and must be submitted:

    Field::inst("email") ->validator(Validate::email(ValidateOptions::inst() ->allowEmpty(false) ->optional(false)));

    A join with dbValues ​​which will accept an empty value, which is stored as null on the database:

    Field::inst("users.site") ->options(Options::inst() ->table("sites") ->value("id") ->label("name")) ->validator( Validate::dbValues()),

    Allow only certain values ​​to be submitted:

    Field::inst("group") ->validator(Validate::values(array("CSM", "FTA", "KFVC")))

    The following shows a complete Editor example with validation methods applied:

    Ditor::inst($db, "staff") ->fields(Field::inst("first_name") ->validator(Validate::notEmpty(ValidateOptions::inst() ->message("A first name is required "))), Field::inst("last_name") ->validator(Validate::notEmpty(ValidateOptions::inst() ->message("A last name is required"))), Field::inst(" position"), Field::inst("email") ->validator(Validate::email(ValidateOptions::inst() ->message("Please enter an e-mail address"))), Field::inst( "office"), Field::inst("extn"), Field::inst("age") ->validator(Validate::numeric()) ->setFormatter(Format::ifEmpty(null)), Field: :inst("salary") ->validator(Validate::numeric()) ->setFormatter(Format::ifEmpty(null)), Field::inst("start_date") ->validator(Validate::dateFormat(" Y-m-d")) ->getFormatter(Format::dateSqlToFormat("Y-m-d")) ->setFormatter(Format::dateFormatToSql("Y-m-d"))) ->process($_POST) ->json();

    Global validators

    You may also find it useful to be able to define a global validator that will execute whenever a request is made to the server and the Editor->process() method is executed. This method can be used to provide security access restrictions, validate input data as a whole or even to check that a user is logged in before processing the request.

    Function

    The function that is given to the Editor->validator() method has the following signature:

  • $editor - The Editor instance that the function is being executed for.
  • $action - The action being performed - this will be one of:
    • Editor::ACTION_READ - Read / get data
    • Editor::ACTION_CREATE - Create a new record
    • Editor::ACTION_EDIT - Edit existing data
    • Editor::ACTION_DELETE - Delete existing row(s)
    • Editor::ACTION_UPLOAD - Upload a file.
  • $data - The data submitted by the client.
  • The return value from the function should be a string if the validation fails, where the string returned is the error message to show the end user. If the validation passes, return an empty string, null or simply have no return statement.

    Note that this function is executed only once when the Editor->process() method is called, rather than once per submitted row. Also, as of Editor 1.9, it is possible to add multiple validation functions by calling Editor->validator() multiple times, just as with the field validators. The given validators will run sequentially.

    Examples // Allow read only access based on a session variable Editor::inst($db, "table") ->fields(...) ->validator(function ($editor, $action, $data) ( if ( $action !== Editor::ACTION_READ && $_SESSION["read_only"]) ( return "Cannot modify data"; ) )) ->process($_POST) ->json(); // Create and edit with dependent validation Editor::inst($db, "table") ->fields(...) ->validator(function ($editor, $action, $data) ( if ($action == = Editor::ACTION_CREATE || $action === Editor::ACTION_EDIT) ( foreach ($data["data"] as $pkey => $values) ( if ($values["country"] === "US " && $values["location"] === "London UK") ( return "London UK is not in the US"; ) ) ) )) ->process($_POST) ->json(); PHP API documentation

    The PHP API developer documentation for the Editor PHP classes is available for detailed and technical discussion about the methods and classes discussed above.

    Related publications