如何优化以下PHP代码?
<?php
if(strlen($_POST['myName']) < 2 || isNumeric($_POST['myName']))
{
echo "Please fill in your name!";
exit();
}
if(!is_numeric($_POST['myAge']) || strlen($_POST['myAge'] < 1))
{
echo "Please enter only digits!";
exit();
}
if(strlen($_POST['myRes']) < 2 || isNumeric($_POST['myRes']))
{
echo "Please enter something!";
exit();
}
echo "Hi " . $_POST['myName'] . "! you are " . $_POST['myAge'] . " years old and live in " . $_POST['myRes'] . "? Nice to meet you!";
?>
如果我想测试100个输入怎么办?如何以最佳方式进行测试?
答案 0 :(得分:8)
不了解速度,但从风格的角度来看,你的代码可以像这样改进(当然是很多可能的方法之一)。
function p($key) {
return isset($_POST[$key]) ? trim($_POST[$key]) : null;
}
$name = p('myName');
$age = intval(p('myAge'));
$res = p('myRes');
$err = array();
if(!preg_match('~^\w{3,}+$~', $name))
$err[] = "Please fill in your name!";
if($age < 3 || $age > 99)
$err[] = "Please enter a valid age";
if(!preg_match('~^\w{3,}+$~', $res))
$err[] = "Please fill in your location!";
if($err)
echo implode("<br>", $err);
else
echo "Hi $name! you are $age years old and live in $res? Nice to meet you!";
注意重点
答案 1 :(得分:1)
嗯..实际上你应该在使用任何$ _POST变量之前添加isset()
的检查,然后你可以更改strlen($_POST['myAge'] < 1)
(注意你的)
位置错误了)到empty($_POST['myAge'])
答案 2 :(得分:1)
如果您要进行表单验证,请尝试http://docs.jquery.com/Plugins/validation#Validate_forms_like_you.27ve_never_been_validating_before.21 它是客户端,所以你仍然需要某种服务器端验证,但这总是让我更容易