简体   繁体   English

用于密码验证的PHP Regex在不同环境中失败

[英]PHP Regex for password validation failing in different environment

We're using the below function to validate passwords as per customer requirements. 我们使用以下功能根据客户要求验证密码。 This works in our dev environment as well as the customers staging environment but when pushing to production passwords fail randomly. 这适用于我们的开发环境以及客户登台环境,但是当推送到生产密码时,随机失败。 Staging and production is suppose to be identical and making it very difficult to figure out why it's not working as we do not have access to the production environment. 暂存和生产假设是相同的,并且很难弄清楚它为什么不起作用,因为我们无法访问生产环境。

The password needs to validate the following: 密码需要验证以下内容:

  1. At least 1 upper-case and 1 lower-case alpha character 至少1个大写字母和1个小写字母字符
  2. At least 1 numeric digit (0-9) 至少1位数字(0-9)
  3. At least 10 characters long 至少10个字符
  4. Contains 1 of the following characters - !@#$%^&*() ( Shift + any numeric digit on a Standard US Keyboard) 包含以下字符中的一个 - !@#$%^&*()Shift +标准美国键盘上的任何数字)
  5. Should be in no particular order as long as the above validates 只要以上验证,应该没有特别的顺序

The code works in our dev environment so it may work for you as well. 代码在我们的开发环境中工作,因此它也适用于您。 What we need is to look at why it may fail and 我们需要的是看看它为什么会失败

<?php
function isStrongPassword($pass, $char = 10) {
     $bits = ['A-Z', 'a-z', '0-9',preg_quote('#$%^&*()','/')];
         if (is_numeric($char) && strlen($pass) >= $char) {
              foreach ($bits AS $bit) {
                  if (preg_match('@[' . $bit . ']@', $pass) == false) {
                      return false;
                  }
              }
              return true;
          }
          return false;
       }
?>

Translating my comment into an answer. 将我的评论翻译成答案。

It seems all the code in answer can be translated into a single regex using lookaheads as this: 似乎所有代码中的代码都可以使用lookaheads转换为单个正则表达式,如下所示:

/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%^&*()]).{10,}$/

Each of 4 lookaheads (?=...) ensures presence of an uppercase letter, lowercase letter, digit and a special character. 4个前瞻(?=...)每一个都确保存在大写字母,小写字母,数字和特殊字符。 .{10,} ensures minimum length is 10 for input. .{10,}确保输入的最小长度为10。

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

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