PHP Classes

PHP Sanitize Class: Validate and sanitize string values

Recommend this page to a friend!
  Info   View files Example   View files View files (19)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2024-01-10 (2 months ago) RSS 2.0 feedNot enough user ratingsTotal: 394 This week: 1All time: 6,621 This week: 571Up
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  
Name: Leo Daidone <contact>
Classes: 2 packages by
Country: Argentina Argentina
Age: 45
All time rank: 323542 in Argentina Argentina
Week rank: 420 Up3 in Argentina Argentina Up

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  
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

  Files folder image Files  /  examples  
File Role Description
Files folder imagefactories (1 file)
  Accessible without login Plain text file example_1.php Example example1
  Accessible without login Plain text file example_2.php Example example2

  Files folder image Files  /  examples  /  factories  
File Role Description
  Accessible without login Plain text file SanitizerEmail.php Example Example Sanitizer

  Files folder image Files  /  exceptions  
File Role Description
  Accessible without login Plain text file InvalidCustomNameException.php Aux. Exception

  Files folder image Files  /  factories  
File Role Description
  Plain text file AbstractSanitizer.php Class AbstractClass
  Plain text file ISanitizer.php Class Interface
  Plain text file SanitizerFloat.php Class Sanitizer
  Plain text file SanitizerHtml.php Class Sanitizer
  Plain text file SanitizerInt.php Class Sanitizer
  Plain text file SanitizerLdap.php Class Sanitizer
  Plain text file SanitizerParanoid.php Class Sanitizer
  Plain text file SanitizerSql.php Class Sanitizer
  Plain text file SanitizerSystem.php Class Sanitizer
  Plain text file SanitizerUtf8.php Class Sanitizer

 Version Control Unique User Downloads Download Rankings  
 100%
Total:394
This week:1
All time:6,621
This week:571Up