开发者

php built-in filter

I want to make a little contact form, where the user i开发者_如何转开发nputs his name, email, and the message. The form is submitted with ajax to a php file that has to do the following:

1- check if the 3 posted variables exist and not NULL 2- sanitize and verify the 3 variables for malicious code and some criteria, like the name must be and the email must be.. 3- send the data with php's mail().

how can I achieve the first and the second steps with php filter

NB: I took a look at the php's manual and I understood nothing.

Thanks.


1. Use isset() or array_key_exists() on $_POST to see if values exist.

if (isset($_POST['a_field']))

// or

if (array_key_exists('a_field', $_POST))

You can also use filter_has_var, but it's also got a "gotcha" that you need to be aware of. It does not work off of PHP's superglobals, instead relying on the data that's sent to PHP. If you manually declare something in your script, e.g. $_POST['test'], filter_has_var will not see it.

How to use filter_has_var:

if (filter_has_var(INPUT_POST, 'test'))



2. Do you want to sanitize data or validate it? (two different things).

Assert that name and email have values, and that email is a valid email:

if (!empty($_POST['name']))

if (!empty($_POST['email']) && filter_input(INPUST_POST, 'email', FILTER_VALIDATE_EMAIL))


you can do this for email:

filter_var('name@domain.com', FILTER_VALIDATE_EMAIL)

Returns the filtered data, or FALSE if the filter fails.

you can for just validate the value do this with array.

$args = array(
    'name'   => array('filter'    => FILTER_VALIDATE_BOOLEAN,
                            'flags'     => FILTER_NULL_ON_FAILURE),
    'email'    => array('filter'    => FILTER_VALIDATE_BOOLEAN,
                            'flags'     => FILTER_NULL_ON_FAILURE),
     'message'    => array('filter'    => FILTER_VALIDATE_BOOLEAN,
                            'flags'     => FILTER_NULL_ON_FAILURE));

$myinputs = filter_input_array(INPUT_GET, $args);

you can add multi filter or multi flag to one field like this

email => array("filter" => array(FILTER_VALIDATE_EMAIL ,FILTER_VALIDATE_BOOLE)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜