我有一个清除用户输入的功能。返回clean输入后,它会通过json_decode($ var,true);目前,我收到了格式错误的字符串错误。但是,如果我将其打印出来并使用http://jsonlint.com/进行测试,它就会通过。我已经意识到清洁过程之后的字符串是149个字符串,之前是85个。为了解决这个问题,我还通过正则表达式来删除特殊字符,但我想这可能会撤消之前的内容功能呢。 “new”函数是否撤消了filer_var的作用?这是清理输入的最佳方法吗?以下是我的代码:
#index.php
$cleanInput = cleanse->cleanInput($_POST);
#cleanse.php OLD
function cleanInput($input){
foreach($input as $key => $value){
$cleanInput[$key] = filter_var($value, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH));
}
return($cleanInput); //Returns 149char long string, visually 85chars
}
#cleanse.php NEW
function cleanInput($input){
foreach($input as $key => $value){
$cleanInput[$key] = preg_replace("[^+A-Za-z0-9]", "", filter_var($value, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH)));
}
return($cleanInput); //Returns 85char long string, visually 85chars
}
#outputs
#Before
{"name":"Pete Johnson","address":"123 main street","email":"myemail@gmail.com","password":"PA$$word"}
#After
{"name":"Pete Johnson","address":"123 main street","email":"myemail@gmail.com","password":"PA$$word"}
答案 0 :(得分:3)
对filter_var($ value,FILTER_SANITIZE_STRING,FILTER_FLAG_STRIP_HIGH)的函数调用会创建如下输出:
{"name":"Pete Johnson","address":"123 mainstreet","email":"myemail@gmail.com","password":"PA$$word"}
这就是json_decode不起作用的原因。
像我在评论中所说的那样。最好的办法是最初在输入上使用json_decode,然后使用HTML_Purifier和Zend_Validator遍历各个元素,或编写自己的元素来处理各个字段。例如,电子邮件的验证要求与密码不同。编辑:
我试过运行新功能,但我无法让它工作。所以我做了一些调整才能让它发挥作用。虽然我不确定这是否是你想要的正则表达式。以下是我从此代码输出的内容:
$input = '{"name":"Pete Johnson","address":"123 main street","email":"myemail@gmail.com","password":"PA$$word"}';
$cleanedInput = preg_replace("/[^+A-Za-z0-9]/", "", filter_var($input, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH));
echo $cleanedInput;
输出:
34name3434PeteJohnson3434address3434123mainstreet3434email3434myemailgmailcom3434password3434PAword34