Speed up development with full-stack environments for every branch.

Learn More

How to validate a variable using filter_var function()

110 Runs 1499 Views 89 Copies
Saved

Saved

gtsolutions 373

gtsolutions
published 4 years ago

<?php

/**
 * PHP filter module
 * validate a variable with a specific filter usin filter_var() function
 */

// for filters that accept options, use this format
$options = array(
    'options' => array(
        'min_range' => 0
    ),
    'flags' => FILTER_FLAG_ALLOW_OCTAL,
);
$var = '0976';
$filter = filter_var('0976', FILTER_VALIDATE_INT, $options);
if ($filter)
    echo '<div style="background-color:green;padding:10px;color:#fff;font-size:16px;">
            <b>' . $var . '</b> is a valid integer
          </div><br />';
else
    echo '<div style="background-color:red;padding:10px;color:#fff;font-size:16px;">
            <b>' . $var . '</b> is not a valid integer
          </div><br />';

// for filter that only accept flags, you can pass them directly
$var = 'TRUE';
$filter = filter_var($var, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if ($filter)
    echo '<div style="background-color:green;padding:10px;color:#fff;font-size:16px;">
            <b>' . $var . '</b> is a valid boolean
          </div><br />';
else
    echo '<div style="background-color:red;padding:10px;color:#fff;font-size:16px;">
            <b>' . $var . '</b> is not a valid boolean
          </div><br />';

// for filter that only accept flags, you can also pass as an array
$var = 'why';
$filter = filter_var($var, FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE));
if ($filter)
    echo '<div style="background-color:green;padding:10px;color:#fff;font-size:16px;">
            <b>' . $var . '</b> is a valid boolean
          </div><br />';
else
    echo '<div style="background-color:red;padding:10px;color:#fff;font-size:16px;">
            <b>' . $var . '</b> is not a valid boolean
          </div><br />';

// callback validate filter
function foo($value) {
    // expected format: only lowercasse
    if (ctype_lower($value))
        return $value;
    else
        return false;
}

$var = "aaaaaoff";
$filter = filter_var($var, FILTER_CALLBACK, array('options' => 'foo'));
//var_dump($filter);
if ($filter)
    echo '<div style="background-color:green;padding:10px;color:#fff;font-size:16px;">
            <b>' . $var . '</b> contains only lowercasse letters
          </div>';
else
    echo '<div style="background-color:red;padding:10px;color:#fff;font-size:16px;">
            <b>' . $var . '</b> does not contains only lowercasse letters
          </div>';
?>
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).