Data Sanitization

Web developers will tell you that you should never trust data submitted by a browser without proper validation. Failing to properly validate your input data can make your applications and web sites susceptibility to cross-site script attacks.

To help developers safeguard their applications we have created the RaxanDataSantizer class with a number of methods that can be used to validate and sanitize input/output values.

Server-Side HTML5 Validation

The HTML5 specification includes a number of new form controls and validation constraints for the web browser. This means that an HTML5 browser will be able to validate a web form based before it's submitted to the server. But wouldn't it be great if we could just use those same HTML5 form controls and validation constraints on the server? Would it not make things much simpler? That's exactly what we did.

Basic HTML5 validation was added to the framework to make it easier to validate client inputs. With just a single lines of code, you can check for valid inputs:

<?php
    protected function addItem($e){
        $isFormValid = $this->webForm->checkValidity();
    }
?>

Here's another example showing how you can use the checkValidity() method to valid a web form:

<?php
    protected function addItem($e){
        $frm = $this->webForm;
        if ( !$frm->checkValidity(true,'required') ) {
            $this->flashmsg('Invalid input values');
        } else {
            $v = $frm->validValues();
            // some code here....
            $this->flashmsg('New item added');
        }
    }
?>

The following markup can can be used to validate the web form on both server and client:

<form name="webForm" action="" method="post">
    <input type="text" name="itemname" id="itemname" value="" maxlength="50" required />
    <textarea name="description" id="description" cols="10" rows="5" maxlength="250" required></textarea>
    <input type="submit" name="submit1" id="submit1" value="Submit" />
</form>

Supported HTML5 Validation constraints:

• Maxlength
• Required
• Min / Max (only works with type=number)
• Email
• URL
• Number
• Date
• Month
• Pattern

Sanitize POST/GET Values

To sanitize post back (POST) or query string (GET) values use the "post" and "get" objects as shown below:

<?php

    require_once('raxan/pdi/autostart.php');

    class NewPage extends RaxanWebPage {

        protected function saveInfo($e) {
            // retrieve values from a form post
            $name = $this->post->textVal('full_name');   // get text value (removes all html)
            $dob = $this->post->dateVal('date_of_birth','mysql');    // get date value (in mysql format)
            $age = $this->post->intVal('age');       // get integer value
            $amount = $this->post->floatVal('amount');   // get float value

            $value = $this->post->value('comment');   // get unsanitized post back value

            // retrieve text value by field name.  Same as textVal($fieldName)
            $note = $this->post->personalNote; 

            // retrieve values submitted via the query string (e.g.  path/to/page.php?index=100)
            $index = $this->get->intVal('index');

            // returns an array of post values after applying the text sanitizer
            $data = $this->post->filterValues();

            // only return comma (,) separated list of field names
            $data = $this->post->filterValues('subject,message'); 

            // returns an array after applying alphanumeric and text sanitizer
            $data = $this->post->filterValues(array('postalcode'=>'alphanumeric','gender'=>'text')); 

        }

    }

?>

Note: Both the "post" and "get" objects returns an instance of the RaxanDataSantizer class.

To sanitize form element values use the either textVal(), intVal() or floatVal() methods:

<?php

    require_once('raxan/pdi/autostart.php');

    class NewPage extends RaxanWebPage {

        protected function _config() {
            $this->preserveFormContent = true; // preserve form content
        }

        protected function saveInfo($e) {
            $name = $this->fullname->textVal()  // get text value from an element with id=fullname
            $age = $this->age->intVal()         // get integer value
            $amount = $this->age->floatVal()    // get float value

            $value = $this->text1->val();       // get unsanitized value
        }

    }

?>

To sanitize event values returned from the client use the textVal(), intVal() or floatVal() methods on the event object:

<?php

    require_once('raxan/pdi/autostart.php');

    class NewPage extends RaxanWebPage {

        protected function _config() {
            $this->$preserveFormContent = true; // preserve form content
        }

        protected function deleteUser($e) {
            $text = $e->textVal()       // get text value
            $int= $e->intVal()          // get integer value
            $float = $e->floatVal()     // get float value

            $value = $e->value();       // get unsanitized value
        }

    }

?>

It's important to note that the methods intVal(), floatVal() and dateVal() will return NULL if the value being requested is invalid. For example, if a user submits the value "100abc" the intVal() and floatVal() will return NULL.

In some cases you might want the intVal() and floatVal() methods return a zero (0) value. To do this you can use the Bitwise "Or" operator as shown below:

<?php

    require_once('raxan/pdi/autostart.php');

    class NewPage extends RaxanWebPage {

        protected function saveData($e) {

            $qty = $this->post->intVal('qty') | 0; // defaults to 0
            $price = $this->post->floatVal('price') | 0; // defaults to 0

        }

    }

?>

Sanitize Output Values

To sanitize output value you can use the text(), textval(), intval() and and floatval() methods on the element object:

<?php

    require_once('raxan/pdi/autostart.php');

    class NewPage extends RaxanWebPage {

        protected function _config() {
            $this->$preserveFormContent = true; // preserve form content
        }

        protected function showInfo($e) {

            $data = getUserInfo();

            $this->fullname->textVal($data->name);  // set text value (removes all html)
            $this->age->intVal($data->age);         // set integer value
            $this->amount->floatVal($data->amount); // set float value

            $this->descript->val($data->desc);      // set unsanitized value

            $this->comment->text($data->comment);   // set text value
            $this->summary->html($data->summary);   // sets the inner html value (unsanitized)

        }

    }

?>

Sanitize Array Value

To sanitize the values inside an associated array can use the Raxan::dataSanitizer() method:

<?php

    require_once('raxan/pdi/autostart.php');

    class NewPage extends RaxanWebPage {

        protected function _config() {
            $this->$preserveFormContent = true; // preserve form content
        }

        protected function showInfo($e) {


            $row = getRecord(1);
            $row = $this->Raxan->dataSanitizer($row);

            $street = $row->text('street');
            $country = $row->text('country');

        }

    }

?>

Validating Form Input

The following shows how to use the isEmail() method to valid an email address:

<?php

    require_once('raxan/pdi/autostart.php');

    class NewPage extends RaxanWebPage {
        protected function saveForm($e) {
            if (!$this->post->isEmail('text1')) $msg = 'Please enter a valid email address';
            else $msg = 'You have entered a valid email address';

            $this->flashmsg($msg, 'bounce'); // flash message to browser

        }
    }
?>

<div class="flashmsg"></div>
<form name="form1" action="" method="post">
    <label>Enter a valid email address:</label><br />
    <input type="text" name="text1" id="text1" value="" />
    <input type="submit" name="submit1" id="submit1" value="Submit" xt-bind="click,saveForm"/>
</form>

Data Sanitizer methods

Use the follow methods to sanizer user input values

  • textVal - Returns text value after removing the html tags
  • intVal - Returns an interger if value is numeric or null if there was an error
  • floatVal - Returns float if value is numeric or null if there was an error.
  • dateVal - Returns a date/time string value based on the $format parameter or null if value is not a valid date.
  • emailVal - Returns sanitized email address or an empty string if input value is not a valid email address
  • escapeVal - Returns text with special html/xml characters encoded
  • htmlVal - Returns sanitized html text value by removing inline style sheets, script tags and inline events
  • matchVal - Returns characters that matches the specified regex pattern
  • timestampVal - Returns unix timestamp if input value is a valid datetime string or null if there was an error
  • urlVal - Returns sanitized url

Use the following methods to format integer, float, money and date values.

  • formatDate - Returns formated date value
  • formatMoney - Returns formatted money value based on locale settings
  • formatNumber - Returns formatted number value based on locale settings

Use to following methods to validate user input values.

  • isDate - Returns true if the input value is a valid date
  • isEmail - Returns true if the input value is a valid email address
  • isNumeric - Returns true if the input value is numeric
  • isUrl - Returns true if the input value is a valid url

See RaxanDataSanitizer for additional properties and methods .


Up Next Database Connection