PHP filter_var_array Example

This is a very simple PHP contact form validation script.

It fails silently, based on the expectation the client is validating the data prior to submitting it. In this case, if the server receives invalid inputs, inputs with invalid data, or a data set missing required inputs, it is assumed the data is either not being submitted by the expected client code, or it has been tampered with en route.

The silent fail is a die with no output. This provides no information for potentially malicious visitors.

If the data is valid, it is echoed back to the server JSON encoded.

if (isset($_POST) && !empty($_POST)) {
        $required = array('name', 'email', 'interest', 'relationship', 'message');
        $optional = array('phone', 'subscribe');
        $inputs = array_merge($required, $optional);
        foreach ($_POST as $k => $v) {
                if (!in_array($k, $inputs)) {
                        die;
                }
                $v = trim($v);
                if (!empty($v)) {
                        $data[$k] = $v;
                } else {
                        if (in_array($k, $required)) {
                                die;
                        } else {
                                $data[$k] = '';
                        }
                }
        }

        $filter = filter_var_array($data, array(
                'name' => array('filter' => FILTER_VALIDATE_REGEXP,
                                'options' => array('regexp' => '/^[ \w\,\.\'\-]{5,}$/')),
                'email' => FILTER_VALIDATE_EMAIL,
                'interest' => array('filter' => FILTER_VALIDATE_REGEXP,
                                'options' => array('regexp' => '/^(Sales|Support)$/')),
                'relationship' => array('filter' => FILTER_VALIDATE_REGEXP,
                                'options' => array('regexp' => '/^(Client|Partner|Vendor)$/')),
                'subscribe' => array('filter' => FILTER_VALIDATE_REGEXP,
                                'options' => array('regexp' => '/^(on)?$/')),
                'message' => array('filter' => FILTER_VALIDATE_REGEXP,
                                'options' => array('regexp' => '/^[\w\,\.\'\-\(\)\$ ]{5,}$/')),
                'phone' => array('filter' => FILTER_VALIDATE_REGEXP,
                                'options' => array('regexp' => '/^(1[ \-\.])?(\d{3})?[ \-\.]?\d{3}[ \-\.]?\d{4}$/'))));

        if ($filter === false || in_array(false,$filter)) {
                die;
        }
        echo json_encode($filter);
}

In an environment where security is important (security is important in all environments), this code should be extended to include a unique token validation, where a token is sent to the client on the initial request and the next request must have the identical token or it will be considered invalid.