Home > Backend Development > PHP Tutorial > PHP如何校验不合法的输入

PHP如何校验不合法的输入

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 20:08:58
Original
876 people have browsed it

问题如下:从浏览器端传来的参数中包含id这样的字段,问题是用户给id='12345dfg'这样的值以后,php后端会执行intval('$id')给它转换为整数,然而php转换过程中id就被转换成了合法的输入id=12345,如何把上述错误的输入校验出来呢?

问题补充:如果是$id = $request->getPost('id','int'),这种情况下,我该如何校验用户输入是否合法啊?

回复内容:

问题如下:从浏览器端传来的参数中包含id这样的字段,问题是用户给id='12345dfg'这样的值以后,php后端会执行intval('$id')给它转换为整数,然而php转换过程中id就被转换成了合法的输入id=12345,如何把上述错误的输入校验出来呢?

问题补充:如果是$id = $request->getPost('id','int'),这种情况下,我该如何校验用户输入是否合法啊?

用参数过滤函数,filter_var($id, FILTER_VALIDATE_INT),正确的整数返回数字,错误的返回false。

PHP自带的函数is_int判断是否为整数;

is_numeric — 检测变量是否为数字或数字字符串
is_int — 检测变量是否是整数

function getPost($parameter,$type){
    switch($type){
        case 'int' : return (int)$_POST[$parameter];
        case 'string': return (string)$_POST[$parameter];
        case 'array': retrun  is_array($_POST[$parameter])?$_POST[$parameter]:array();
        ……………………
    }
}
Copy after login

Related labels:
php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template