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

Learn More

How to validate input variables using filter_input function()

303 Runs 5773 Views 725 Copies
Saved

Saved

gtsolutions 373

gtsolutions
published 4 years ago

<?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>';
?>
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).