如何防止输入数组 [英] How to protect against input arrays
问题描述
我有一个程序.它接受字母数字字符串的输入(我已经检查过).
因此有效输入为www.example.com/myfile.php?input=John1
I have a program. It accepts an input of a alphanumeric string (which I already do checks for).
So a valid input would be www.example.com/myfile.php?input=John1
但是,如果有人键入www.example.com/myfile.php?input[]
,那么它将中断整个程序的逻辑中断,因为我不接受输入作为数组.我如何才能确定用户输入的内容仅仅是一个字符串.不是数组,还是其他任何数据类型/结构?
However, if someone were to type in www.example.com/myfile.php?input[]
then it breaks my entire program's logic breaks because I don't accept input as an array. How can I unsure the thing a user enters is just a string. Not an array, or any other data types/structures?
推荐答案
解决此问题的方法缓慢而乏味,其中涉及许多手动类型检查.希望在整个应用程序中都写出if (!is_string($foo))
条件来磨损键盘.
There is the slow and tedious way of solving this problem, which involves a lot of manual type-checking. Expect to wear your keyboard out writing if (!is_string($foo))
conditions throughout your application.
或者您可以使用为解决此确切问题而设计的离子发生器.
Or you could use Ionizer which was designed for solving this exact problem.
<?php
use ParagonIE\Ionizer\GeneralFilterContainer;
use ParagonIE\Ionizer\Filter\{
StringFilter,
WhiteList
};
// Define properties to filter:
$ic = new GeneralFilterContainer();
$ic->addFilter(
'username',
(new StringFilter())->setPattern('^[A-Za-z0-9_\-]{3,24}$')
)
->addFilter('passphrase', new StringFilter())
->addFilter(
'domain',
new WhiteList('US-1', 'US-2', 'EU-1', 'EU-2')
);
// Invoke the filter container on the array to get the filtered result:
try {
// $post passed all of our filters.
$post = $ic($_POST);
} catch (\TypeError $ex) {
// Invalid data provided.
}
如果有人尝试传递数组而不是字符串,则$ic($_POST)
会引发TypeError
,然后您可以优雅地捕获,记录和失败.
If someone attempts to pass an array instead of a string, $ic($_POST)
throws a TypeError
which you can then catch, log, and fail gracefully.
这篇关于如何防止输入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!