POST清理并避免嵌套if块

时间:2017-09-11 16:34:37

标签: php

当清理从控制器传递给模型的$ _POST时,我需要清理输入,我可以想到两个选项。

对于第一个,我可以像这样嵌套if块:

if(!empty($username))
{
            if(!empty($password))
            {
              //login the user
            }
            else 
            {
                echo 'Please enter password.'
            }
 }
 else 
 {
    echo 'Please enter username.'
 }

另一个是这样的:

   if(empty($username))
    {
        $err[] = 'Please enter username';                
    }
    if(empty($password))
    {
        $err[] = 'Please enter password.';                
    }
    if(empty($err)){
        //login the user
    }
    else
    {
        //display error
    }

哪种方式是首选方式,是否有另一种更智能的方法来消毒输入?

2 个答案:

答案 0 :(得分:1)

只需使用:

$errors = [];
if(!isset($_POST['username']) || empty($_POST['username'])) {
    $errors[] = 'Please enter valid username';
} else if(!isset($_POST['password']) || empty($_POST['password'])) {
    $errors[] = 'Please enter valid password';
}

filter_var可用于过滤特定输入。

答案 1 :(得分:0)

这不是消毒,你只是检查输入中是否有任何字符。消毒是指为您的表单获取确切的价值类型。

如果你的问题是你是否可以创建一个预期输入名称数组

if (numberOfTriangles < possibleFloatingTriangles) {
  var randomIndices = [];

  while (randomIndices.length < possibleFloatingTriangles - numberOfTriangles) {
    var randomNumber = Math.ceil(Math.random()*150);
    if (randomIndices.indexOf(randomNumber) > -1) continue;
    randomIndices[randomIndices.length] = randomNumber;
  }

  scene.traverse(function (node) {
    if (numberOfTriangles >= possibleFloatingTriangles) return;

    if (node instanceof THREE.Mesh && node.geometry.type === "PlaneGeometry") {
      for(var i = 0; i < node.geometry.faces.length; i++) {
        if(randomIndices.indexOf(i) != -1) {
          var currentFace = node.geometry.faces[i];
          var triangleGeometry = new THREE.Geometry();

          // I assumed they might be getting referenced here initially hence the clone()
          var p1 = node.geometry.vertices[currentFace.a].clone();
          var p2 = node.geometry.vertices[currentFace.b].clone();
          var p3 = node.geometry.vertices[currentFace.c].clone();

          triangleGeometry.vertices.push(p1);
          triangleGeometry.vertices.push(p2);
          triangleGeometry.vertices.push(p3);

          var face = new THREE.Face3(0,2,1);

          triangleGeometry.faces.push(face);

          var triangleMaterial = new THREE.MeshPhongMaterial({ color: 0xff0000, wireframe: showWireframe, specular: 0x0, morphTargets: true, flatShading: true, side: THREE.DoubleSide });
          var triangle = new THREE.Mesh(triangleGeometry, triangleMaterial);

          triangle.rotation.set(-Math.PI/2, Math.PI/2000, Math.PI); ;

          scene.add(triangle);
        }
      }
    }
  }
}

对于消毒,您可以查看以下答案; https://stackoverflow.com/a/34760018/502649

此外,消毒的最佳做法是RegExfilter_var