Example #1
0
 /**
  * Lists all filters available with the filter extension.
  */
 public function doListFilters()
 {
     $list = filter_list();
     foreach ($list as $filter) {
         echo filter_id($filter), ": {$filter}<br />\n";
     }
 }
 /**
  * Gets all possible filter types
  *
  * @return array
  */
 static function getRegisteredFilters()
 {
     if (empty(self::$filtersTypes)) {
         foreach (filter_list() as $filter_name) {
             self::$filtersTypes[filter_id($filter_name)] = $filter_name;
         }
     }
     return self::$filtersTypes;
 }
Example #3
0
function _filter_var_array_is_valid_filter($filter)
{
    static $ids = null;
    if ($ids === null) {
        // A bit painful in php, exposing the IDs might be better if this is hot
        $ids = array_fill_keys(array_map('filter_id', filter_list()), null);
    }
    return array_key_exists($filter, $ids);
}
Example #4
0
 public function getServer($key = null, $default = null)
 {
     var_dump($this->filters);
     die;
     if (null === $key) {
         return filter_list(INPUT_SERVER) ? filter_input_array(INPUT_SERVER) : $this->params;
     }
     return filter_has_var(INPUT_SERVER, $key) ? filter_input(INPUT_SERVER, $key) : $default;
 }
Example #5
0
/**
 * ( excerpt from http://docs.hhvm.com/manual/en/function.filter-var-array.php )
 *
 * This function is useful for retrieving many values without repetitively
 * calling filter_var().
 *
 * @data       mixed   An array with string keys containing the data to
 *                     filter.
 * @definition mixed   An array defining the arguments. A valid key is a
 *                     string containing a variable name and a valid value
 *                     is either a filter type, or an array optionally
 *                     specifying the filter, flags and options. If the
 *                     value is an array, valid keys are filter which
 *                     specifies the filter type, flags which specifies any
 *                     flags that apply to the filter, and options which
 *                     specifies any options that apply to the filter. See
 *                     the example below for a better understanding.
 *
 *                     This parameter can be also an integer holding a
 *                     filter constant. Then all values in the input array
 *                     are filtered by this filter.
 * @add_empty  mixed   Add missing keys as NULL to the return value.
 *
 * @return     mixed   An array containing the values of the requested
 *                     variables on success, or FALSE on failure. An array
 *                     value will be FALSE if the filter fails, or NULL if
 *                     the variable is not set.
 */
function filter_var_array($data, $definition = null, $add_empty = true)
{
    if (!is_array($data)) {
        trigger_error('filter_var_array() expects parameter 1 to be array, ' . gettype($data) . ' given', E_WARNING);
        return null;
    }
    $default_filter = null;
    if (!is_array($definition)) {
        if ($definition === null) {
            $default_filter = FILTER_DEFAULT;
        } else {
            if (is_int($definition)) {
                // A bit painful in php, exposing the IDs might be better if this is hot
                $ids = array_fill_keys(array_map('filter_id', filter_list()), null);
                if (!array_key_exists($definition, $ids)) {
                    return false;
                }
                $default_filter = $definition;
            } else {
                return false;
            }
        }
        $definition = array_fill_keys(array_keys($data), null);
    }
    $ret = array();
    foreach ($definition as $key => $def) {
        if ($key === "") {
            trigger_error('filter_var_array(): Empty keys are not allowed in the ' . 'definition array', E_WARNING);
            return false;
        }
        if (!array_key_exists($key, $data)) {
            if ($add_empty) {
                $ret[$key] = null;
            }
            continue;
        }
        $value = $data[$key];
        if ($default_filter) {
            $ret[$key] = _filter_var_array_single($value, $default_filter);
            continue;
        }
        if (!is_array($def)) {
            $ret[$key] = _filter_var_array_single($value, $def);
            continue;
        }
        if (!isset($def['filter'])) {
            $filter = FILTER_DEFAULT;
        } else {
            $filter = $def['filter'];
        }
        $ret[$key] = _filter_var_array_single($value, $filter, $def);
    }
    return $ret;
}
 /**
  * Validate Form Input
  *
  * This function is used during the processing of the form data to validate
  * each added field and the value contained in that field against the set datatypes, 
  * lengths, and if they are required.
  */
 private function checkInput($post)
 {
     if (empty($this->fields) || empty($post)) {
         trigger_error("Required data for validating missing.", E_USER_WARNING);
         return false;
     }
     // Loop over data and validate it
     foreach ($post as $key => $val) {
         /**
          * Make sure only defined fields were submitted an nothing else.
          * If this error keeps happening, make SURE you created all input fields
          * using the addField() method and not manually.
          */
         if (!isset($this->fields[$key])) {
             $this->errors[] = "The form you submitted doesn't appear to be valid.\n" . "Please notify an administrator if this problem continues. [{$key}]\n";
             return false;
         }
         // Verify required fields have been filled in
         if ($this->fields[$key]['required'] === true && empty($val)) {
             $this->errors[] = "The \"{$key}\" field is required and cannot be empty!\n";
             return false;
         }
         // Make sure value isn't longer than the field maxlength
         if ($this->fields[$key]['maxlength'] < strlen(trim($val)) && !empty($this->fields[$key]['maxlength'])) {
             $this->errors[] = "Somehow you entered more data than permitted for the " . "\"{$key}\" field!\n";
             return false;
         }
         // Validate field Datatype
         // Current types are 'email', 'letters','alphanumeric', 'numbers', 'phone', or 'any'
         /**
          * Check Email Address
          * Takes a given email address and split it into the username and domain,
          * then verifies the domain name is valid.  See functions.php for a more
          * comprehensive email validation function if this isn't sufficient.
          */
         if ($this->fields[$key]['datatype'] == 'email' && !empty($val)) {
             list($userName, $mailDomain) = explode("@", $val);
             if (!checkdnsrr($mailDomain, "MX") || strlen($userName) < 2) {
                 $this->errors[] = "Sorry, but your email address {$val} couldn't be validated.\n";
                 return false;
             }
         }
         // Check for letters, spaces, and '.', '-', '_' only.
         if ($this->fields[$key]['datatype'] == 'letters' && !empty($val)) {
             if (!preg_match('/^([a-zA-Z\\.-_ ]+)$/', $val)) {
                 $this->errors[] = "The '{$key}' field only allows letters!  Please remove anything else.";
                 return false;
             }
         }
         // Check for numbers, spaces, and '.', '-', '_' only.
         if ($this->fields[$key]['datatype'] == 'numbers' && !empty($val)) {
             if (!preg_match('/^([0-9\\.-_ ]+)$/', $val)) {
                 $this->errors[] = "The '{$key}' field only allows numbers!  Please remove anything else.";
                 return false;
             }
         }
         // Check for letters, numbers, spaces, and '.', '-', '_' only.
         if ($this->fields[$key]['datatype'] == 'alphanumeric' && !empty($val)) {
             if (!preg_match('/^([#0-9a-zA-Z\\.-_ ]+)$/', $val)) {
                 $this->errors[] = "The '{$key}' field only allows letters and numbers!  Please remove anything else.";
                 return false;
             }
         }
         // Check Phone Number - Allows either 123-456-7890 or 456-7890 format
         if ($this->fields[$key]['datatype'] == 'phone' && !preg_match('/^([0-9]{3}-)?([0-9]{3})-([0-9]{4})$/', $val) && !empty($val)) {
             $this->errors[] = "The number {$val} is an invalid phone number format.\n" . "Make sure you enter a number in this format: 501-555-1234\n";
             return false;
         }
         /**
          * Clean the input data
          *
          * This part uses php's Filter extension which must be installed and
          * requires PHP version 5.2.
          * This function removes and converts potentially harmful characters from
          * post data such as <>, etc.
          */
         if (!function_exists('filter_list') || !in_array('string', filter_list())) {
             trigger_error("A required function doesn't exist!  Please notify the administrator.", E_USER_ERROR);
             exit;
         }
         $this->fields[$key]['value'] = filter_var($val, FILTER_SANITIZE_STRING);
     }
     // Return true on success
     return true;
 }
Example #7
0
<?php

//$body=file_get_contents('php://input');
//var_dump($body);
//http_response_code(202);
//print_r($_SERVER);
echo <<<HTML
<html>
<body onload="return false;">
<form id='redirectForm' method='POST' action='/done.html'>
<input type='hidden' name='status' value='complete'/>
<input type='hidden' name='id' value='0u812'/>
<input type='submit' value='Please Click Here To Continue'/>
</form>
</body>
</html>
HTML;
//virtual('d');
//print_r(get_browser());
var_export(filter_list());
var_dump(filter_has_var(INPUT_GET, 'test'));
Example #8
0
 protected function getPHPFilterName($id)
 {
     foreach (filter_list() as $name) {
         if (filter_id($name) == $id) {
             return $name;
         }
     }
     if (filter_id($id) === FALSE) {
         return FALSE;
     }
     return $id;
 }
Example #9
0
 public function getList()
 {
     return filter_list();
 }
Example #10
0
 /** {@inheritdoc} */
 public function validate()
 {
     if (empty(self::$rules)) {
         return false;
         // no rules; defaults to FALSE
     }
     // initialize filter & validator
     $filters = ['php' => filter_list(), 'validated' => [], 'filter' => [], 'filter_plugin' => null, 'validator' => [], 'validator_plugin' => null];
     if (class_exists(ZEND_STATIC_VALIDATOR)) {
         $filters['validator_plugin'] = forward_static_call([ZEND_STATIC_VALIDATOR, 'getPluginManager']);
         $filters['validator'] = $filters['validator_plugin']->getRegisteredServices()['invokableClasses'];
     }
     if (class_exists(ZEND_STATIC_FILTER)) {
         $filters['filter_plugin'] = forward_static_call([ZEND_STATIC_FILTER, 'getPluginManager']);
         $filters['filter'] = $filters['filter_plugin']->getRegisteredServices()['invokableClasses'];
     }
     foreach (self::$rules as $k => $v) {
         $newValue = $value = $v['property']->getValue($this);
         $hasValue = !is_blank($value);
         foreach ($v['rules'] as $rule) {
             // e.g. [full_special_chars('flags' => FILTER_FLAG_NO_ENCODE_QUOTES)]
             //      [HtmlEntities('quotestyle' => ENT_QUOTES, 'encoding' => 'UTF-8', 'doublequote' => true)]
             //      [StringLength('max' => 255, 'message' => 'Hi, ntd1712')]
             preg_match(CHAOS_MATCH_RULE_ITEM, $rule, $matches);
             if (!isset($matches[1])) {
                 continue;
             }
             $rule = strtolower($matches[1]);
             $options = [];
             if (!empty($matches[2])) {
                 $result = @eval('return array' . $matches[2] . ';');
                 if (null === error_get_last() && is_array($result)) {
                     $options = $result;
                     if (isset($options['message'])) {
                         $options['message'] = str_replace('{property}', $k, $options['message']);
                     }
                 }
             }
             // validator
             if ('notempty' === $rule || $hasValue) {
                 if (in_array($rule, $filters['validator'])) {
                     /** @var \Zend\Validator\AbstractValidator $validator */
                     $validator = $filters['validator_plugin']->get($rule, $options);
                     $filters['validated'][$rule] = true;
                     if (!$validator->isValid($value)) {
                         return $validator->getMessages();
                     }
                 } elseif (in_array($rule, $filters['php'])) {
                     $result = filter_var($value, filter_id($rule), $options);
                     $filters['validated'][$rule] = true;
                     if (false === $result) {
                         return [sprintf('Value of "%s" is not valid for "%s"', 32 < strlen($value) ? substr($value, 0, 20) . '...' : $value, $k)];
                     }
                 }
             }
             // filter
             if (!isset($filters['validated'][$rule]) && $hasValue) {
                 if (in_array($rule, $filters['filter'])) {
                     /** @var \Zend\Filter\AbstractFilter $filter */
                     $filter = $filters['filter_plugin']->get($rule, $options);
                     $newValue = $filter->filter($value);
                 } elseif (in_array($rule, $filters['php'])) {
                     $result = filter_var($value, filter_id($rule), $options);
                     if (false !== $result) {
                         $newValue = $result;
                     }
                 }
                 // set new property value (if any)
                 if ($value != $newValue) {
                     $v['property']->setValue($this, $newValue);
                 }
             }
         }
     }
     return false;
 }
Example #11
0
 /**
  * 判别类型的准确的常量表示
  * @param string $type 含糊的类型表述
  */
 public static function detectType($type)
 {
     $type = empty($type) ? 'string' : strtolower($type);
     foreach (filter_list() as $name) {
         if (ends_with($name, $type)) {
             return filter_id($name);
         }
     }
 }
 /**
  * Sanitize and validate a variable contained in a name space
  *
  * @param string $varName       the name of a variable defined in the namespace
  * @param mixed  $default       a default value if variable is not set. NULL means that
  *                              the variable is mandatory.
  * @param mixed  $validator     Can be:
  *                                1) null use default validation
  *                                2) an integer representing a simple Validate filter without flags and options
  *                                3) an array representing a Validate filter with flags and/or options
  *                                4) an instance of an object that expose function 'assert'.
  *                                   you can use istance of Respect\Validation\Validator
  * @param mixed  $sanitizer     Can be:
  *                                A) null if no sanitization is required
  *                                B) an integer representing a simple Sanitize filter without flags and options
  *                                C) an array representing a Sanitize filter with flags and/or options
  *                                D) a callable that accept an argument (the source) and return sanitized one 
  * 
  * @throws InvalidArgumentException if $varName is not defined and $default not provided
  * @throws Exception if validator fails to validate variable (depending from the validator)
  * @throws InvalidArgumentException if sanitize fails
  * 
  * @return mixed the sanitized value associated to varName in namespace
  * 
  * LIMITS:
  *  sanitizer are supported just on scalar values
  *  non scalar value require a custom validator like Respect\Validator
  * 
  */
 public function getValue($varName, $default = null, $validator = null, $sanitizer = null)
 {
     // prepare a static array to validate validators and sanitizer filters
     static $validFilters = null;
     //load once runtime
     if (is_null($validFilters)) {
         // prepare a list of valid filters: do once
         $validFilters = array();
         $filters = filter_list();
         foreach ($filters as $filter_name) {
             $validFilters[filter_id($filter_name)] = $filter_name;
         }
         // Remove unsupported filters:
         foreach (array(FILTER_VALIDATE_BOOLEAN, FILTER_CALLBACK) as $badFilter) {
             unset($validFilters[$badFilter]);
         }
     }
     // Ensure var exists or a default value is present
     if (!$varName || is_null($default) && !isset($this->varStore[$varName])) {
         throw new InvalidArgumentException("Missing mandatory parameter {$varName}.", 400);
     }
     $sourceValue = isset($this->varStore[$varName]) ? $this->varStore[$varName] : $default;
     $scalarValue = is_scalar($sourceValue);
     // manage NULL_AS_DEFAULT
     if ($sourceValue === self::NULL_AS_DEFAULT) {
         $sourceValue = null;
     }
     // sanitize the variable value (if requested )
     if (is_null($sanitizer)) {
         // CASE A: sanitizing not required
         $sanitizedValue = $sourceValue;
     } elseif (is_int($sanitizer) && array_key_exists($sanitizer, $validFilters) && $scalarValue) {
         // CASE B: Use a simple sanitize filter
         $sanitizedValue = filter_var($sourceValue, $sanitizer);
     } elseif (is_array($sanitizer) && isset($sanitizer['filter']) && array_key_exists($sanitizer['filter'], $validFilters) && $scalarValue) {
         // CASE C: use sanitizer filter with flags and/or options
         $filter = $sanitizer['filter'];
         $sanitizedValue = filter_var($sourceValue, $filter, $sanitize);
         // should I unset($sanitizer['filter']) ?
     } elseif (is_callable($sanitizer)) {
         $sanitizedValue = $sanitizer($sourceValue);
     } else {
         throw new InvalidArgumentException("Invalid sanitizer filter on {$varName}.", 400);
     }
     //Now we are sure that variable has a sanitized value: validate it (if requested )
     if (is_null($validator)) {
         // CASE 1: validation not required
         $valid = $scalarValue ? filter_var($sanitizedValue) : $sanitizedValue;
         $validatorName = 'DEFAULT';
     } elseif (is_int($validator) && array_key_exists($validator, $validFilters) && $scalarValue) {
         // CASE 2: Use a simple validation filter
         $valid = filter_var($sanitizedValue, $validator);
         $validatorName = $validFilters[$validator];
     } elseif (is_array($validator) && isset($validator['filter']) && array_key_exists($validator['filter'], $validFilters) && $scalarValue) {
         // CASE 3: use validation filter with flags and/or options
         $filter = $validator['filter'];
         $valid = filter_var($sanitizedValue, $filter, $validator);
         // should unset($validator['filter'])?
         $validatorName = $validFilters[$filter];
     } elseif (is_object($validator)) {
         // CASE 4: the object must expose assert() method (like in Respect\Validation library )
         try {
             $validator->assert($sanitizedValue);
             // N.B. is up to custom validator test the value type
             $valid = true;
         } catch (Exception $e) {
             $validatorName = 'OBJECT_VALIDATOR';
             $valid = false;
             $errorMsg = $e->getMessage();
         }
     } else {
         $validatorName = 'unsupported';
         $valid = false;
     }
     // thrown exception if not validate value
     if (false === $valid) {
         if (empty($errorMsg)) {
             $val = $scalarValue ? $sanitizedValue : 'structured';
             $errorMsg = "Invalid value({$val}) for {$validatorName} filter on [{$varName}]";
         }
         throw new InvalidArgumentException($errorMsg, 400);
     }
     return $sanitizedValue;
 }
Example #13
0
 static function detectType($F)
 {
     $F = empty($F) ? 'string' : strtolower($F);
     foreach (filter_list() as $A) {
         if (ends_with($A, $F)) {
             return filter_id($A);
         }
     }
 }
Example #14
0
<?php

var_dump(filter_list());
var_dump(filter_list(array()));
echo "Done\n";
Example #15
0
 /**
  * 获取全部过滤器方法
  *
  * @return multitype:number
  */
 public function filterAction()
 {
     $map = array();
     $map['int'] = '整数验证';
     $map['boolean'] = '是非验证';
     $map['float'] = '浮点验证';
     $map['validate_url'] = '是否URL';
     $map['validate_email'] = '是否Email';
     $map['validate_ip'] = '是否IP地址';
     $map['string'] = '过滤字符串';
     $map['encoded'] = '去除或编码特殊字符';
     $map['special_chars'] = 'HTML转义';
     $map['unsafe_raw'] = '无过滤字符串';
     $map['email'] = '过滤非Email字符';
     $map['url'] = '过滤非URL字符';
     $map['number_int'] = '数字过滤非整型';
     $map['number_float'] = '数字过滤非浮点';
     $map['magic_quotes'] = '转义字符';
     $filters = array();
     foreach (filter_list() as $key => $value) {
         if (isset($map[$value])) {
             $filters[] = array('name' => $map[$value], 'val' => filter_id($value));
         }
     }
     $filters[] = array('name' => '关闭过滤器', 'val' => 0);
     return $this->rst($filters, null, true);
 }
Example #16
0
function test_filters()
{
    /***
     * Data Filtering Using PHP's Filter Functions - Part one
     * Examples using PHP's Filter Functions
     * http://devolio.com/blog/archives/413-Data-Filtering-Using-PHPs-Filter-Functions-Part-one.html
     **/
    error_reporting(E_ALL);
    /* do a quick check to make sure that the filter list is available */
    if (function_exists('filter_list')) {
        /* filter list found */
    } else {
        die("Error: Filters not found.");
    }
    /* variables to test against */
    $int = 432;
    $bool = true;
    $float = 432.43;
    $reg = "/^([a-zA-Z0-9 ]){4,16}\$/";
    $url = "http://devolio.com/blog";
    $email = '*****@*****.**';
    $ipaddr = '127.0.0.1';
    $ipres = "192.168.0.*";
    $ipv6addr = "2001:0db8:85a3:08d3:1319:8a2e:0370:7334";
    $string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX\n\tYZ1234\t567890`~!@#\$%^&*()-_=+[{]};:'\"<,>.?/\\|\\n\\r\\t";
    /* grab all of the filters and show them */
    echo "<h2>Filter list</h2><pre>";
    echo "<ul>\n";
    $filters = filter_list();
    foreach ($filters as $filter) {
        echo "<li>" . $filter . "</li>\n";
    }
    echo "</ul></pre>\n";
    echo "<h2>FILTER_VALIDATE_*</h2>";
    /* check if an integer is valid */
    $valid_int = filter_var($int, FILTER_VALIDATE_INT);
    echo "<pre><b>FILTER_VALIDATE_INT</b><br>";
    if ($valid_int !== false) {
        echo "Valid integer.</pre>";
    } else {
        echo "Not a valid integer.</pre>";
    }
    /* check if a boolean is valid */
    $valid_bool = filter_var($bool, FILTER_VALIDATE_BOOLEAN);
    echo "<pre><b>FILTER_VALIDATE_BOOL</b><br>";
    if ($valid_bool !== false) {
        echo "Valid boolean.</pre>";
    } else {
        echo "Not a valid boolean.</pre>";
    }
    /* check if a float (int) is valid */
    $valid_float = filter_var($float, FILTER_VALIDATE_FLOAT);
    echo "<pre><b>FILTER_VALIDATE_FLOAT</b><br>";
    if ($valid_float !== false) {
        echo "Valid float.</pre>";
    } else {
        echo "Not a valid float.</pre>";
    }
    /* check if a regular expression is valid
     * suppressed (bug?) in case regex not available
     */
    $valid_reg = @filter_var($reg, FILTER_VALIDATE_REGEXP);
    echo "<pre><b>FILTER_VALIDATE_REGEXP</b><br>";
    if ($valid_reg !== false) {
        echo "Valid regular expression.</pre>";
    } else {
        echo "Not a valid regular expression.</pre>";
    }
    /* check if a URL is valid */
    $valid_url = filter_var($url, FILTER_VALIDATE_URL);
    echo "<pre><b>FILTER_VALIDATE_URL</b><br>";
    if ($valid_url !== false) {
        echo "Valid URL.</pre>";
    } else {
        echo "Not a valid URL.</pre>";
    }
    /* check if an e-mail address is valid */
    $valid_email = filter_var($email, FILTER_VALIDATE_EMAIL);
    echo "<pre><b>FILTER_VALIDATE_EMAIL</b><br>";
    if ($valid_email !== false) {
        echo "Valid e-mail address.</pre>";
    } else {
        echo "Not a valid e-mail address.</pre>";
    }
    /* check if an IP address is valid */
    $valid_ip = filter_var($ipaddr, FILTER_VALIDATE_IP);
    echo "<pre><b>FILTER_VALIDATE_IP</b><br>";
    if ($valid_ip !== false) {
        echo "Valid IP address.</pre>";
    } else {
        echo "Not a valid IP address.</pre>";
    }
    echo "<h2>FILTER_SANITIZE_*</h2>";
    /* sanitize filters */
    /* check if filter unsafe raw is unsafe. protip: YES */
    $raw = $string;
    $valid_raw = filter_var($raw, FILTER_UNSAFE_RAW);
    echo "<pre><b>FILTER_UNSAFE_RAW</b><br>" . $valid_raw . "</pre>";
    /* sanitize string */
    $san_string = filter_var($string, FILTER_SANITIZE_STRING);
    echo "<pre><b>FILTER_SANITIZE_STRING</b><br>" . $san_string . "</pre>";
    /* sanitize stripped */
    $san_stripped = filter_var($string, FILTER_SANITIZE_STRIPPED);
    echo "<pre><b>FILTER_SANITIZE_STRIPPED</b><br>" . $san_stripped . "</pre>";
    /* sanitize encoded */
    $san_enc = filter_var($string, FILTER_SANITIZE_ENCODED);
    echo "<pre><b>FILTER_SANITIZE_ENCODED</b><br>" . $san_enc . "</pre>";
    /* sanitize special chars */
    $san_spc = filter_var($string, FILTER_SANITIZE_SPECIAL_CHARS);
    echo "<pre><b>FILTER_SANITIZE_SPECIAL_CHARS</b><br>" . $san_spc . "</pre>";
    /* sanitize email */
    $san_email = filter_var($string, FILTER_SANITIZE_EMAIL);
    echo "<pre><b>FILTER_SANITIZE_EMAIL</b><br>" . $san_email . "</pre>";
    /* sanitize url */
    $san_url = filter_var($string, FILTER_SANITIZE_URL);
    echo "<pre><b>FILTER_SANITIZE_URL</b><br>" . $san_url . "</pre>";
    /* sanitize int */
    $san_int = filter_var($string, FILTER_SANITIZE_NUMBER_INT);
    echo "<pre><b>FILTER_SANITIZE_NUMBER_INT</b><br>" . $san_int . "</pre>";
    echo "<h2>FILTER_FLAG_*</h2>";
    /* filter flags */
    /* strip low - strips ascii < 32 */
    $strip_low = filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
    echo "<pre><b>FILTER_FLAG_STRIP_LOW</b><br>" . $strip_low . "</pre>";
    /* strip high - strips ascii > 127 */
    $strip_high = filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
    echo "<pre><b>FILTER_FLAG_STRIP_HIGH</b><br>" . $strip_high . "</pre>";
    /* encode low - encodes ascii < 32 */
    $enc_low = filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
    echo "<pre><b>FILTER_FLAG_ENCODE_LOW</b><br>" . $enc_low . "</pre>";
    /* encode high - encodes ascii > 127 */
    $enc_high = filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_HIGH);
    echo "<pre><b>FILTER_FLAG_ENCODE_HIGH</b><br>" . $enc_high . "</pre>";
    /* don't encode ' or " */
    $deq = filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
    echo "<pre><b>FILTER_FLAG_NO_ENCODE_QUOTES</b><br>" . $deq . "</pre>";
    var_dump('ORIGINAL STRING: ', $string);
    var_dump('ORIGINAL INT: ', $int);
}
Example #17
0
 /**
  * Filters data using PHP's filter extension
  * 
  * @see filter_var()
  * @param mixed $data
  * @param mixed $filter
  * @param mixed $options
  * @param bool $falseOnFail
  * @return mixed
  */
 function filter($data, $filter = null, $options = null, $falseOnFail = true)
 {
     if (is_array($data)) {
         // the $filter must be an array or a string to an array defined under app.filters.rules
         if (is_string($filter)) {
             if (($rules = Atomik::get("helpers.filters.rules.{$filter}", false)) === false) {
                 throw new AtomikException('When $data is an array, the filter must be an array of definition or a defination name in filter()');
             }
         } else {
             $rules = $filter;
         }
         $results = array();
         $messages = array();
         $validate = true;
         foreach ($rules as $field => $params) {
             if (isset($data[$field]) && is_array($data[$field])) {
                 if (($results[$field] = $this->filter($data[$field], $params)) === false) {
                     $messages[$field] = Atomik::get('helpers.filters.messages', array());
                     $validate = false;
                 }
                 continue;
             }
             $filter = FILTER_SANITIZE_STRING;
             $message = Atomik::get('helpers.filters.default_message', 'The %s field failed to validate');
             $required = false;
             $default = null;
             $label = $field;
             if (is_array($params)) {
                 // extracting information from the array
                 if (isset($params['message'])) {
                     $message = Atomik::delete('message', $params);
                 }
                 if (isset($params['required'])) {
                     $required = Atomik::delete('required', $params);
                 }
                 if (isset($params['default'])) {
                     $default = Atomik::delete('default', $params);
                 }
                 if (isset($params['label'])) {
                     $label = Atomik::delete('label', $params);
                 }
                 if (isset($params['filter'])) {
                     $filter = Atomik::delete('filter', $params);
                 }
                 $options = count($params) == 0 ? null : $params;
             } else {
                 $filter = $params;
                 $options = null;
             }
             if (!isset($data[$field]) && !$required) {
                 // field not set and not required, do nothing
                 continue;
             }
             if ((!isset($data[$field]) || $data[$field] == '') && $required) {
                 // the field is required and either not set or empty, this is an error
                 $results[$field] = false;
                 $message = Atomik::get('helpers.filters.required_message', 'The %s field must be filled');
             } else {
                 if ($data[$field] === '' && !$required) {
                     // empty but not required, null value
                     $results[$field] = $default;
                 } else {
                     // normal, validating
                     $results[$field] = $this->filter($data[$field], $filter, $options);
                 }
             }
             if ($results[$field] === false) {
                 // failed validation, adding the message
                 $messages[$field] = sprintf($message, $label);
                 $validate = false;
             }
         }
         Atomik::set('helpers.filters.messages', $messages);
         return $validate || !$falseOnFail ? $results : false;
     }
     if (is_string($filter)) {
         if (in_array($filter, filter_list())) {
             // filter name from the extension filters
             $filter = filter_id($filter);
         } else {
             if (preg_match('@/.+/[a-zA-Z]*@', $filter)) {
                 // regexp
                 $options = array('options' => array('regexp' => $filter));
                 $filter = FILTER_VALIDATE_REGEXP;
             } else {
                 if (($callback = Atomik::get("helpers.filters.callbacks.{$filter}", false)) !== false) {
                     // callback defined under app/filters/callbacks
                     $filter = FILTER_CALLBACK;
                     $options = $callback;
                 }
             }
         }
     }
     return filter_var($data, $filter, $options);
 }
 public function getList() : array
 {
     return filter_list();
 }
Example #19
0
	<meta http-equiv="Cache-Control" content="max-age=3600, public">
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>PHP Filter</title>
	<meta name="Content-Language" content="de" />
	<meta name="language" content="Deutsch" />
	<meta name="author" content="Andre Kasper, M.Sc.">
	<meta name="viewport" content="width=device-width,initial-scale=1.0">
</head>
<body>
	<table>
		<tr>
			<td>Filter Name</td>
			<td>Filter ID</td>
		</tr>
		<?php 
foreach (filter_list() as $id => $filter) {
    echo '<tr><td>' . $filter . '</td><td>' . filter_id($filter) . '</td></tr>';
}
?>
	</table>
	<?php 
$email1 = 'andre.kasper.@th-koeln.de<"';
$email2 = '*****@*****.**';
//$email1 = filter_var($email1, FILTER_SANITIZE_EMAIL);
if (!filter_var($email1, FILTER_VALIDATE_EMAIL) === false) {
    echo 'E-Mail ' . $email1 . ' erfolgreich validiert!<br />';
} else {
    echo 'E-Mail ' . $email1 . ' ist keine gültige Adresse!<br />';
}
if (!filter_var($email2, FILTER_VALIDATE_EMAIL) === false) {
    echo 'E-Mail ' . $email2 . ' erfolgreich validiert!<br />';
Example #20
0
<?php

include 'header.php';
?>

<div class="container">
<div class="row">
	<div class="col-md-3">
		<h1>PHP 5 FILTERS</h1>
	</div>
	<div class="col-md-6">
<?php 
//php5 filters printed
echo '<pre>';
print_r(filter_list());
echo '</pre>';
//http://phphulp.jorendewit.nl/view/24/4/
?>

	</div>
 
	<div class="col-md-3">
		<h1></h1>
	</div>
</div>

 <div class="row">
	<div class="col-md-12">
	
	<?php 
//filter voor nummer
Example #21
0
 /**
  * Finds the filter name by filter id
  * 
  * @param int $filterId
  * @return string
  * @throws SanitizationException
  */
 private function findFilter($filterId)
 {
     foreach (filter_list() as $filterName) {
         if (filter_id($filterName) === $filterId) {
             return $filterName;
         }
     }
     throw new \Exception('Could not find filter ' . $filterId);
 }
Example #22
0
 /**
  * 过滤参数
  * @param mixed $value
  * @param string $type
  * @param mixed $default
  * @param mixed $filter
  * @param mixed $options
  * @return mixed
  */
 private static function filter($value, $type = null, $default = '', $filter = null, $options = null)
 {
     //获取系统默认的过滤器
     if (!isset(self::$_defaultFilters)) {
         self::$_defaultFilters = filter_list();
     }
     // 默认强制转换为字符串
     if (is_null($type) && self::$AUTO_STRING) {
         $type = 's';
     }
     $filters = isset($filter) ? $filter : self::$FILTER;
     if ($filters) {
         if (is_string($filters)) {
             if (0 === strpos($filters, '/')) {
                 if (1 !== preg_match($filters, (string) $value)) {
                     // 支持正则验证
                     return isset($default) ? $default : null;
                 }
             } elseif (strpos($filters, ',')) {
                 $filters = explode(',', $filters);
             } else {
                 $filters = [$filters];
             }
         } elseif (is_int($filters)) {
             $filters = [$filters];
         }
         if (is_array($filters)) {
             foreach ($filters as $filter) {
                 if (function_exists($filter)) {
                     $value = is_array($value) ? array_map_recursive($filter, $value) : $filter($value);
                     // 参数过滤
                 } else {
                     if (is_int($filter)) {
                         $filter = isset(self::$_defaultFilters[$filter]) ? $filter : null;
                     } else {
                         $filter = filter_id($filter) ?: null;
                     }
                     $value = filter_var($value, $filter);
                     if (false === $value) {
                         return isset($default) ? $default : null;
                     }
                 }
             }
         }
     }
     if (!empty($type)) {
         switch (strtolower($type)) {
             case 'a':
                 // 数组
                 $value = (array) $value;
                 break;
             case 'd':
                 // 数字
                 $value = (int) $value;
                 break;
             case 'f':
                 // 浮点
                 $value = (double) $value;
                 break;
             case 'b':
                 // 布尔
                 $value = (bool) $value;
                 break;
             case 's':
                 // 字符串
             // 字符串
             default:
                 $value = (string) $value;
         }
     }
     return $value;
 }
Example #23
0
<?php

/**
 * @copyright Copyright (C) 2005-2008 eZ systems as. All rights reserved.
 * @license http://ez.no/licenses/new_bsd New BSD License
 * @version 1.4
 * @filesource
 * @package UserInput
 * @subpackage Tests
 */
?>
<html>
<head><title>Test 3</title></head>
<body>
<?php 
var_dump(filter_list());
$cb1 = filter_input(INPUT_GET, 'test1', filter_id('boolean'), FILTER_NULL_ON_FAILURE);
$cb2 = filter_input(INPUT_GET, 'test2', filter_id('boolean'));
$int1 = filter_input(INPUT_GET, 'test3', filter_id('int'), FILTER_NULL_ON_FAILURE);
$int2 = filter_input(INPUT_GET, 'test4', filter_id('int'), array('flags' => FILTER_NULL_ON_FAILURE, 'options' => array('max_range' => 42)));
if ($cb1 && $cb2) {
    echo "both are checked";
}
var_dump($cb1, $cb2, $int1, $int2);
?>
<form method="get" align="center">
<input type="checkbox" name="test1" checked="yes"/>
<input type="checkbox" name="test2"/>
<input type="text" name="test3"/>
<input type="text" name="test4"/>
<input type="submit" name="submit" value="Go!"/>
Example #24
0
 /**
  * Validates the definition array $definition.
  *
  * Before reading the values from the input source, the definition array
  * can be validated by this method to check whether all necessary
  * elements are correctly formed.
  *
  * With the following code you can check whether the definition is valid:
  * <code>
  * <?php
  * if ( ( $returnValue = ezcInputForm::validateDefinition( $definition ) ) !== true )
  * {
  *     // do something with the error type and error message in $returnValue
  * }
  * else
  * {
  *     // the definition was correct
  * }
  * ?>
  * </code>
  *
  * @param array $definition
  * @return array|bool If the definition is correct the method returns
  *                    boolean true. When an error is found the function
  *                    returns an array where the first element is the type,
  *                    and the second element the error message.
  */
 public static function validateDefinition($definition)
 {
     // The definition parameter should be an array
     if (!is_array($definition)) {
         return array(ezcInputForm::DEF_NO_ARRAY, "The definition array is not an array");
     }
     // There should be atleast one element
     if (count($definition) === 0) {
         return array(ezcInputForm::DEF_EMPTY, "The definition array is empty");
     }
     foreach ($definition as $name => $element) {
         // Each element should be an ezcInputFormDefinitionElement
         if (!$element instanceof ezcInputFormDefinitionElement) {
             return array(ezcInputForm::DEF_ELEMENT_NO_DEFINITION_ELEMENT, "The definition for element '{$name}' is not an ezcInputFormDefinitionElement");
         }
         // The first value in an element should be REQUIRED or OPTIONAL
         if (!in_array($element->type, array(ezcInputFormDefinitionElement::OPTIONAL, ezcInputFormDefinitionElement::REQUIRED), true)) {
             return array(ezcInputForm::DEF_NOT_REQUIRED_OR_OPTIONAL, "The first element definition for element '{$name}' is not ezcInputFormDefinitionElement::OPTIONAL or ezcInputFormDefinitionElement::REQUIRED");
         }
         // The options should either be an array, a string, or an int
         if ($element->options !== null) {
             $filterOptionsType = gettype($element->options);
             if (!in_array($filterOptionsType, array('integer', 'string', 'array'))) {
                 return array(ezcInputForm::DEF_WRONG_FLAGS_TYPE, "The options to the definition for element '{$name}' is not of type integer, string or array");
             }
             // A callback filter should have the form "string" or "array(string, string)"
             if ($element->filterName == 'callback') {
                 if ($filterOptionsType == 'integer') {
                     return array(ezcInputForm::DEF_WRONG_FLAGS_TYPE, "The callback filter for element '{$name}' should not be an integer");
                 }
                 if ($filterOptionsType == 'array') {
                     if (count($element->options) != 2) {
                         return array(ezcInputForm::DEF_WRONG_FLAGS_TYPE, "The array parameter for the callback filter for element '{$name}' should have exactly two elements");
                     }
                     if (gettype($element->options[0]) != 'string' || gettype($element->options[1]) != 'string') {
                         return array(ezcInputForm::DEF_WRONG_FLAGS_TYPE, "The array elements for the callback filter for element '{$name}' should both be a string");
                     }
                 }
             }
         }
         // The options should either be an int
         if ($element->flags !== null) {
             if (gettype($element->flags) !== 'integer') {
                 return array(ezcInputForm::DEF_WRONG_FLAGS_TYPE, "The flags to the definition for element '{$name}' is not of type integer, string or array");
             }
         }
         // The filter should be an existing filter
         if (!in_array($element->filterName, filter_list())) {
             $filters = join(', ', filter_list());
             return array(ezcInputForm::DEF_UNSUPPORTED_FILTER, "The filter '{$element->filterName}' for element '{$name}' does not exist. Pick one of: {$filters}");
         }
         // The input field name should have a sane format
         if (gettype($name) != 'string') {
             return array(ezcInputForm::DEF_FIELD_NAME_BROKEN, "The element name '{$name}' is not a string");
         }
         if (!preg_match('@^[a-z][a-z0-9_]*$@i', $name)) {
             return array(ezcInputForm::DEF_FIELD_NAME_BROKEN, "The element name '{$name}' has an unsupported format. It should start with an a-z and followed by a-z0-9_");
         }
     }
     return true;
 }
 /**
  * Filter key.
  *
  * @param string $key     Key
  * @param mixed  $default Default = null
  * @param int    $filter  FILTER_* constant
  * @param mixed  $options Filter options
  * @param bool   $deep    Default = false
  *
  * @see http://php.net/manual/en/function.filter-var.php
  *
  * @return mixed
  */
 public function filter($key, $default = null, $filter = FILTER_DEFAULT, $options = array(), $deep = false)
 {
     static $filters = null;
     if (null === $filters) {
         foreach (filter_list() as $tmp) {
             $filters[filter_id($tmp)] = 1;
         }
     }
     if (is_bool($filter) || !isset($filters[$filter]) || is_array($deep)) {
         @trigger_error('Passing the $deep boolean as 3rd argument to the ' . __METHOD__ . ' method is deprecated since version 2.8 and will be removed in 3.0. Remove it altogether as the $deep argument will be removed in 3.0.', E_USER_DEPRECATED);
         $tmp = $deep;
         $deep = $filter;
         $filter = $options;
         $options = $tmp;
     }
     $value = $this->get($key, $default, $deep);
     // Always turn $options into an array - this allows filter_var option shortcuts.
     if (!is_array($options) && $options) {
         $options = array('flags' => $options);
     }
     // Add a convenience check for arrays.
     if (is_array($value) && !isset($options['flags'])) {
         $options['flags'] = FILTER_REQUIRE_ARRAY;
     }
     return filter_var($value, $filter, $options);
 }