php:验证POST的最佳方法 [英] php: best way to validate POST
问题描述
我一直在使用以下代码通过$ _POST验证我的用户输入:
I have been using the code below to validate my user input by $_POST:
if(isset($_POST['name']) && !empty($_POST['name'])) {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
此代码检查是否实际设置了名称",这是显而易见的,明确的并且是必需的. 其次,它检查用户是否在文本字段中键入了某些内容以提供名称值. 但是,如果用户输入SPACE"作为输入,则它会接受它,因为它不为空,它具有SPACE.
This code checks whether 'name' was actually set, which is obvious and clear and needed. Secondly, it checks whether user typed something in textfield to give a value for name. However, if user gives SPACE " " as input it accepts it because it is not empty it has SPACE.
我找到了一种正确的方法:
I found one way of doing it right:
if(isset($_POST['name'])) {
$n = trim($_POST['name']);
if(empty($n)) {
$errors[] = "Please give a name";
}
}
else {
$errors[] = "Please give a name";
}
但是在这里我要重复两次相同的错误消息,那么如何对其进行优化?
But here I am repeating same error message twice, so how can it be optimized?
推荐答案
如果不需要修剪的字符串,则可以将修剪本身移动到if子句:
If you don't need the trimmed string, you can move the trim itself to the if-clause:
if(isset($_POST['name']) && (trim($_POST['name']) != '') ) {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
如果您进一步需要它,可以在检查之前修改输入:
If you further need it, you could modify the input before checking:
$_POST['name'] = trim( $_POST['name'] );
if(isset($_POST['name']) && !empty($_POST['name'])) {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
这篇关于php:验证POST的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!