代码之家  ›  专栏  ›  技术社区  ›  AkiEru

PHP正在摆脱“if”条件并继续下一部分

  •  1
  • AkiEru  · 技术社区  · 11 年前

    我现在正在实现Ajax,服务器端编程语言是PHP。 我需要为我的web应用程序创建一个Ajax表单验证和输入系统。

    $redirectPage = $redirectTime = '';
    
    if($a == 'register') {
        $data = array('name', 'username', 'password', 'gender', 'emailaddress');
        $required = array('name', 'username', 'password');
    
        foreach($data as $field) {
            if(in_array($field, $required) && (!isset($_POST[$field]) || $_POST[$field] == '')) {
                $type = 'danger';
                $message = 'Please enter all required fields.';
                // *1
            } else {
                $$field = $_POST[$field];
            }
        }
    
        // Continue with register process
        // Set the redirectPage and redirectTime for JavaScript setTimeout here
    } else {
        $type = 'warning';
        $message = 'You usually won\'t be able to see this. But if you did, that means you are trying to hack my website!';
        return;
    }
    
    $retval = json_encode(
        array(
            'Type' => $type,
            'Message' => alert($type, $message), // my own function, not important here
            'RedirectPage' => $redirectPage,
            'RedirectTime' => $redirectTime,
        )
    );
    
    echo $retval; // The value here will send back to my Ajax
    

    正如您所看到的,即使post字段不在所需的数组中,我也没有停止句柄过程。最后,它将继续剩下的过程。

    对于*1: 这是我试图在这里放一些保留词的地方。

    继续: 对于一个经验丰富的程序员,您应该注意到,它只会脱离这个if条件,并继续下一个foreach循环。

    出口: 其余的代码不会处理,除非超时,否则绝不会返回到Ajax。

    中断: 我以为它会离开

    if($a == 'register')
    但这并没有发生。

    转到: 我不想被恐龙吃掉,除非这是唯一的办法。

    对于代码的其余部分,添加if条件,检查是否

    $type
    已设置为“危险”: 我不想这样做…(但如果这是唯一的方法…)

    非常感谢。

    2 回复  |  直到 11 年前
        1
  •  2
  •   thoughtrepo    11 年前

    我不完全确定我是否理解这个问题,但我相信可以通过增加一些范围来解决您所面临的问题。我重构了你的代码,希望它能给你指明正确的方向。

    function sendResponse ($type, $message, $redirectPage, $redirectTime) {
    
        $retval = json_encode(
            array(
                'Type' => $type,
                'Message' => alert($type, $message), // my own function, not important here
                'RedirectPage' => $redirectPage,
                'RedirectTime' => $redirectTime,
            )
        );
    
        echo $retval; // The value here will send back to my Ajax
    }
    
    function sendRequiredResponse ($redirectPage, $redirectTime) {
    
        $type = 'danger';
        $message = 'Please enter all required fields.';
    
        sendResponse($type, $message, $redirectPage, $redirectTime);
    }
    
    function sendHackResponse ($redirectPage, $redirectTime) {
    
        $type = 'warning';
        $message = 'You usually won\'t be able to see this. But if you did, that means you are trying to hack my website!';
    
        sendResponse($type, $message, $redirectPage, $redirectTime);
    }
    
    function sendRegisteredResponse ($redirectPage, $redirectTime) {
    
        $type = 'success';
        $message = 'Registration successfull';
    
        sendResponse($type, $message, $redirectPage, $redirectTime);
    }
    
    function register($redirectPage, $redirectTime) {
    
        $data = array('name', 'username', 'password', 'gender', 'emailaddress');
        $required = array('name', 'username', 'password');
    
        foreach($data as $field) {
    
            if(in_array($field, $required) && (!isset($_POST[$field]) || $_POST[$field] == '')) {
    
                /**** registration stops *****/
                return sendRequiredResponse($redirectPage, $redirectTime);
            }
    
            $$field = $_POST[$field];
        }
    
        // Continue with register process
        // Set the redirectPage and redirectTime for JavaScript setTimeout here
    
        sendRegisteredResponse($redirectPage, $redirectTime);
    }
    
    $redirectPage = $redirectTime = '';
    
    if($a === 'register') {
        register($redirectPage, $redirectTime);
    } else {
        sendHackResponse($redirectPage, $redirectTime);
    }
    
        2
  •  1
  •   ArtisticPhoenix    11 年前

    我认为如果你真的想摆脱if,你想要的是一个do-while循环

    http://php.net/manual/en/control-structures.do.while.php

    从文档页面上的第一个示例

    <?php
    do {
        if ($i < 5) {
            echo "i is not big enough";
            break;
        }
        $i *= $factor;
        if ($i < $minimum_limit) {
            break;
        }
       echo "i is ok";
    
        /* process i */
    
    } while (0);
    ?>
    

    然而,我认为这并没有太多用处,因为通常有更好的方法来构造代码。

    后藤也可以使用,但我看到的次数更少 http://php.net/manual/en/control-structures.goto.php

    如果您只是想检查所有字段是否存在 isset 在$_POST中,可以执行array_diff

     $required = array('name', 'username', 'password');
     $missing = array_diff( $required, array_keys($_POST) );
    

    如果您需要检查是否为空,可以使用 array_filter $_POST 但它会算数的 0 同样为空,但您可以创建一个简单的函数来解决这个问题,然后执行array_diff,

    http://php.net/manual/en/function.array-diff.php

    • 返回一个数组,其中包含array1中不存在于任何其他数组中的所有条目。

    通过将所需键的数组用作array1,将array_keys($_POST)用作array2,我们可以获得键的差异,如果返回包含它们存在于所需数组(array1)中但不存在于$_POST中的任何项。

    通过使用 array_filter($_POST) 我们可以从post数组中删除空项,然后执行diff将指示这些项没有值,但是arrayfilter将删除 false, '', 0 数组中的值项。你可以做一个简单的函数

    array_filter( $_POST, function($item){ return $item !== ''; }); 
    

    仅过滤空字符串。

    所以把这些都收集起来你会得到这样的东西

    $required = array('name', 'username', 'password');
    $missing = array_diff(
        $required,
        array_filter(
            $_POST,
            function($item){
                return $item !== '';
            }
        )
    ); 
    
    if( count( $missing ) > 0 ){
        echo 'missing fields: '. implode(', ', $missing );
    }