更新时间:2023-02-23 16:37:26
只是偶然发现了这个问题,但是是相当不安关于使用评估
,我决定继续寻找一个更好的解决方案。
Just stumbled upon this question, but being fairly uneasy about using eval
, I decided to keep looking for a better solution.
我发现又是对PHP的 filter_var $ C另一种奇妙的使用$ C>
功能,传递 FILTER_VALIDATE_BOOLEAN
标志时(的其中有许多)。
What I discovered is yet another wonderful use for PHP's filter_var
function, when passing in the FILTER_VALIDATE_BOOLEAN
flag (of which there are many).
这一条线的功能,似乎在做的很好的安全的字符串(或其他方式)的对象转换为一个布尔值:
This "one line" function seems to do well at safely converting a string (or other) object to a boolean:
<?php
/**
* Uses PHP's `filter_var` to validate an object as boolean
* @param string $obj The object to validate
* @return boolean
*/
function parse_boolean($obj) {
return filter_var($obj, FILTER_VALIDATE_BOOLEAN);
}
和,一个小测试:
/**
* Let's do some testing!
*/
$tests = array (
"yes",
"no",
"true",
"false",
"0",
"1"
);
foreach($tests as $test) {
$bool = parse_boolean($test);
echo "TESTED: ";
var_dump($test);
echo "GOT: ";
var_dump($bool);
echo "\n\n";
}
输出:
/*
TESTED: string(3) "yes"
GOT: bool(true)
TESTED: string(2) "no"
GOT: bool(false)
TESTED: string(4) "true"
GOT: bool(true)
TESTED: string(5) "false"
GOT: bool(false)
TESTED: string(1) "0"
GOT: bool(false)
TESTED: string(1) "1"
GOT: bool(true)
*/
我还没有看够深,但它是可能的,这种解决方案依赖于评估
上下行的地方,但是我还是会使用那些通过纯方评估
ING,因为我认为 filter_var
也将处理通过评估。
I haven't looked deep enough, but it's possible that this solution relies on eval
down the line somewhere, however I'd still side with using those over plain eval
ing since I assume that filter_var
would also handle sanitizing any input before piping it through eval
.