dtc99987 2014-02-19 01:54
浏览 12
已采纳

PHP密码检查器

I have written a password checker using PHP and It worked fine. It consists of many "if else". Is there any way to minimize my usage of "if else" in my code?

function passtest($pass) {
            if (!empty($pass)) { //check if string is empty
                if (ctype_alnum($pass)) { //check if string is alphanumeric
                    if (7 < strlen($pass)){ //check if string meets 8 or more characters
                        if (strcspn($pass, '0123456789') != strlen($pass)){ //check if string has numbers
                            if (strcspn($pass, 'abcdefghijklmnopqrstuvwxyz') != strlen($pass)) { //check if string has small letters
                                if (strcspn($pass, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') != strlen($pass)) { //check if string has capital letters
                                    return "<br />Password passed";
                                }
                                else {
                                    return "<br />No capital letter";
                                }
                            }
                            else {
                                return "<br />No small letter";
                            }
                        }
                        else {
                            return "<br />No number";
                        }
                    }
                    else {
                        return "<br />Password is short";
                    }
                }
                else {
                    return "<br />Password has special character";
                }
            }
            else {
                return "<br />Password field is empty";
            }
        }
  • 写回答

3条回答 默认 最新

  • duanhui7329 2014-02-19 01:59
    关注

    xkcd
    > xkcd

    Your function should just test to see if a password was entered. Other than that, it is not your place to tell people what they can and can't use for a password. How long would it take for a hacker to realise my password is Pokémon, for example? That special character is a HUGE entropy booster.

    That aside, to actually answer your question, try formulating your statements in the negative:

    if( empty($pass)) return "<br />Password field is empty";
    if( !ctype_alnum($pass)) return "<br />Password has special character":
    // ...
    

    This has the handy side-effect of keeping the error messages next to the condition they represent.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染