简体   繁体   English

如何优化此代码?

[英]How can I optimize this code?

How do I optimize the following PHP code? 如何优化以下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!";

?> 

What if I wanted to test, lets say, 100 inputs - how would I do it in the best way? 如果我想测试100个输入,该怎么办-我将如何以最佳方式进行测试?

Don't know about speed, but from the style point of view your code can be improved like this (one of many possible ways of course). 不了解速度,但是从样式的角度来看,您可以像这样改进代码(当然是许多可能的方式之一)。

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!";

Note the important points 注意要点

  • avoid direct access to superglobals like $_POST all over the code 避免在代码中直接访问$ _POST之类的超全局变量
  • use regular expressions to validate strings 使用正则表达式验证字符串
  • force integer conversion when expecting a number 期望数字时强制整数转换
  • avoid exit() 避免exit()
  • use string interpolation instead of concatenation 使用字符串插值而不是串联

嗯..实际上,您应该在使用任何$ _POST变量之前添加对isset()检查,然后可以将strlen($_POST['myAge'] < 1) )更改为empty($_POST['myAge']) (注意,您将)放在错误的位置) empty($_POST['myAge'])

如果您要进行表单验证,请尝试一下http://docs.jquery.com/Plugins/validation#Validate_forms_like_you.27ve_never_been_validating_before.21。它是客户端,因此您仍然需要某种服务器端验证,但这总是让我更容易

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM