Thursday, 29 January 2015

How to validate input variables using filter_input function

<?php

/**
 * PHP filter module
 * validate input variables using filter_input() function
 */
//creating simple POST form
$formPOST = <<<FORM
<form method="POST">
Enter <b>email</b> for POST validation: <input type="text" name="email" value="{$_POST['email']}">
<input type="submit" name="validate" value="validate">
</form>
FORM;

//creating simple GET form
$formGET = <<<FORM
<form method="GET">
Enter <b>url</b> for GET validation: <input type="text" name="url" value="{$_GET['url']}">
<input type="submit" name="validate" value="validate">
</form>
FORM;

echo '<center>';
echo $formPOST;
echo $formGET;

//POST validation
if (isset($_POST['validate']) && trim($_POST['email']) != '') {
    //validate POST input
    $validatePOST = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    echo '<div style="background-color:yellow;padding:10px;color:#000;font-size:16px;">POST METHOD</div>';
    if ($validatePOST) {
        echo '<div style="background-color:green;padding:10px;color:#fff;font-size:16px;">
            <b>' . $_POST['email'] . '</b> is a valid email address
          </div>';
    } else {
        echo '<div style="background-color:red;padding:10px;color:#fff;font-size:16px;">
            <b>' . $_POST['email'] . '</b> is  not a valid email address
          </div>';
    }
}
//GET validation
elseif (isset($_GET['validate']) && trim($_GET['url']) != '') {
    //validate GET input
    $validateGET = filter_input(INPUT_GET, 'url', FILTER_VALIDATE_URL);
    echo '<div style="background-color:yellow;padding:10px;color:#000;font-size:16px;">GET METHOD</div>';
    if ($validateGET) {
        echo '<div style="background-color:green;padding:10px;color:#fff;font-size:16px;">
            <b>' . $_GET['url'] . '</b> is a valid URL
          </div>';
    } else {
        echo '<div style="background-color:red;padding:10px;color:#fff;font-size:16px;">
            <b>' . $_GET['url'] . '</b> is  not a valid URL
          </div>';
    }
}
echo '</center>';


?>
Another important Syntax:
$data   = filter_input(INPUT_POST, 'data', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);

0 comments:

Post a Comment