PHP Classes

PHP Sanitize Class: Validate and sanitize string values

Recommend this page to a friend!
     
  Info   Example   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
Not enough user ratingsTotal: 398 All time: 6,592 This week: 38Up
Version License PHP version Categories
php-sanitize-class 1.0.9GNU General Publi...5.2.0PHP 5, Libraries, Validation, Security
Description 

Author

This package can be used to validate and sanitize string values.

It provides a factory class that can create objects of different classes that can validate and sanitize values of strings of many different types.

Currently it provides classes to validate strings values that can be integer or floating point numbers, HTML, LDAP identifier, SQL, UTF-8 characters, alphanumeric strings, etc..

Custom validator classes can be created by extending AbstractSanitizer class and implementing the ISanitizer interface.

Picture of Leo Daidone
  Performance   Level  

 

Recommendations

Best Package to Address SQL Injection Vulnerabilities
Upgrading security of existing MySQL code

Example

<?php
/**
 * Created by PhpStorm.
 * User: leodaido
 * Date: 1/16/15
 * Time: 3:58 PM
 */

require_once(dirname(__FILE__).'/../ClassLoader.php');
ClassLoader::Register();
$base_path = dirname(__FILE__).'/../';

ClassLoader::Load('PHPSanitizer', $base_path);

$sanitizer = PHPSanitizer::getInstance();

// pretty print function for examples output
function pp($type, $str_valid, $str_invalid, $cleaned_valid, $cleaned_invalid){
    echo
"Validation test for $type Type:\n";
    echo
"==================================\n";
    echo
"Valid String ($str_valid):\n";
    echo
"This is a valid string: ".$str_valid."\n";
    echo
"Cleaned: $cleaned_valid \n";
    echo
"-------------------------------------------------\n";
    echo
"Invalid String ($str_invalid):\n";
    echo
"This is an invalid string: ".$str_invalid."\n";
    echo
"Cleaned: $cleaned_invalid \n";
    echo
"-------------------------------------------------\n";
    echo
"\n\n";
}

echo
"\n";
// PARANOID case
$str_valid = "ThisShouldBeValid";
$str_invalid = "This would be an invalid String 1,2,3...";

pp('PARANOID', $str_valid, $str_invalid, $sanitizer->cleanup($str_valid),$sanitizer->cleanup($str_invalid));

echo
"\n\n";
// SYSTEM case
$str_valid = "This would be an invalid String 1,2,3";
$str_invalid = 'home/user/$ ls -ltra | wc -l 2>1&; (ps aux | grep apache)';

$sanitizer->setType(PHPSanitizer::SYSTEM);

pp('SYSTEM', $str_valid, $str_invalid, $sanitizer->cleanup($str_valid),$sanitizer->cleanup($str_invalid));

echo
"\n\n";
// SQL case
$str_valid = "This would be an invalid String 1,2,3";
$str_invalid = 'SELECT * FROM USERS WHERE 1=1;';

$sanitizer->setType(PHPSanitizer::SQL);

pp('SQL', $str_valid, $str_invalid, $sanitizer->cleanup($str_valid),$sanitizer->cleanup($str_invalid));

echo
"\n\n";
// HTML case
$str_invalid = 'I have lots of <a href="http://my.site.com">links</a> on this <a href="http://my.site.com">page</a> that I want to <a href="http://my.site.com">find</a> the positions.';
$str_valid = htmlentities($str_invalid, ENT_QUOTES);

$sanitizer->setType(PHPSanitizer::HTML);

pp('HTML', $str_valid, $str_invalid, $sanitizer->cleanup($str_valid),$sanitizer->cleanup($str_invalid));

echo
"\n\n";
// INT case
$str_valid = "9223372036854775807";
$str_invalid = '-386.1e';

$sanitizer->setType(PHPSanitizer::INT);

pp('INT', $str_valid, $str_invalid, $sanitizer->cleanup($str_valid),$sanitizer->cleanup($str_invalid));

echo
"\n\n";
// FLOAT case
$str_valid = "9223372036.854775807e-20";
$str_invalid = '1.8e307';

$sanitizer->setType(PHPSanitizer::FLOAT);

pp('FLOAT', $str_valid, $str_invalid, $sanitizer->cleanup($str_valid),$sanitizer->cleanup($str_invalid));

echo
"\n\n";


Details

PHPSanitizer

This package is a set of classes that will help to validate/sanitize the main set of types listed in OWASP, through a PHPSanitizer wrapper class.

It allows to create new validation classes for customs types by extending AbstractSanitizer class and implements ISanitizer interface.

Usage

First, get an instance of PHPSanitizer, you can do that through ClassLoader class:

    ...
    require_once(dirname(__FILE__).'/<path_to_classes>/ClassLoader.php');
    ClassLoader::Register();
    $base_path = dirname(__FILE__).'/<path_to_PHPSanitizer>/';
    
    ClassLoader::Load('PHPSanitizer', $base_path);
    
    $sanitizer = PHPSanitizer::getInstance();
    ...

or just:

    ...
    require_once(dirname(__FILE__).'/<path_to_classes>/PHPSanitizer.php');
    $sanitizer = PHPSanitizer::getInstance();
    ...

by default it uses "PARANOID" validation, you can change type using setType($type, $custom_name, $base_path) method, where $type can be one of:

  • PHPSanitizer::PARANOID
  • PHPSanitizer::SQL
  • PHPSanitizer::SYSTEM
  • PHPSanitizer::HTML
  • PHPSanitizer::INT
  • PHPSanitizer::FLOAT
  • PHPSanitizer::LDAP
  • PHPSanitizer::UTF8
  • PHPSanitizer::CUSTOM

In case of PHPSanitizer::CUSTOM, $custom_name is required following naming rules that will be detailed in Extends section. $base_path is optional. This is used to change default path for Sanitizers classes, defaulted in factories directory under the path to SanitizerFactory class.

There are two method available in $sanitizer instance: validate($string) and cleanup($string)

sanitizer->validate($string); //return a boolean

$sanitizer->cleanup($string); //returns an string with all invalid characters removed

Exteds

To create a new CUSTOM sanitizer, you just need to extend AbstractSanitizer class and implements ISanitizer interface.

    // This file is under examples/factories/.
    require_once(dirname(__FILE__).'/../../factories/AbstractSanitizer.php');
    require_once(dirname(__FILE__).'/../../factories/ISanitizer.php');
    
    class SanitizerEmail extends AbstractSanitizer implements ISanitizer{
        private $pattern = "/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,4})(\]?)$/";
        private $pattern_replace = "/[\;\#\n\r\*\'\"<>&\%\!\(\)\{\}\[\]\?\\/\s,]/";
        private $replacement = "";
    
        public function validate($string){
            return preg_match($this->pattern, $string);
        }
    
        public function cleanup($email){
            $email = trim($email);
            $email = str_replace(" ", "", $email);
            if(count(explode('@',$email))>2){
                throw new Exception('Invalid email address');
            }
            return preg_replace($this->pattern_replace, $this->replacement, $email);
        }
    }

Naming convention


  • Class file name should be camelized, starting with "Sanitizer" followed by type name
  • Class name should be camelized, starting with "Sanitizer" followed by type name
  • Custom name should be camelized type ("Sanitizer" will be added automatically by Factory class)

  Files folder image Files (19)  
File Role Description
Files folder imageexamples (2 files, 1 directory)
Files folder imageexceptions (1 file)
Files folder imagefactories (10 files)
Plain text file ClassLoader.php Class Loader
Accessible without login Plain text file LICENSE Lic. Licence
Plain text file PHPSanitizer.php Class Class
Accessible without login Plain text file README.md Doc. README
Plain text file SanitizerFactory.php Class Factory

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads Download Rankings  
 100%
Total:398
This week:0
All time:6,592
This week:38Up