0

I am working on password validations. All other validations are working fine. I have to add initials validation on password. Password should not contain full name or username and first/last character of username and full name. I am trying to get it with strpos function but it's not working.This is my code i had tried with 2 ways but not working.

<?php

$name = "katlina john smith";
$uname = "testinguser";
$password = "john";
$password = "kjs@123"; // first initials of name
$password = "testing@ps"; //These password format should not be accepted

if (strpos($password,$name) !== false || strpos($password,$uname) !== false) {
    echo 'Username found in the password';
}

//2nd way

if (preg_match("#(($uname)|($name))#", $password))
{
    
     echo 'Username found in the password';
}
parv
  • 95
  • 8
  • try it https://stackoverflow.com/questions/18761201/password-different-than-username-name-email – Leenard Mar 30 '22 at 10:28
  • Swap both value strpos first argument will be your string and the second will the substring you're trying to search.Error is here your if condition should be if (strpos($name,$password) !== false || strpos($uname, $password) !== false) { – Leenard Mar 30 '22 at 10:39

2 Answers2

0

Here is the complete answer

$name = "katlina john smith";
$uname = "testinguser";
$password = "john";
if ( (strpos($name,$password) !== false ) || ( strpos($uname,$password ) !== 
false ) ) {
 echo 'password not valid';
 }
Leenard
  • 63
  • 1
  • 8
  • now it's not working with password="katlina@test123" – parv Mar 30 '22 at 10:58
  • is there not any other way. I have to check all character of name and uname. user should not user any value of name and username in password – parv Mar 30 '22 at 12:05
0

Use this:

$name = "katlina john smith";
$username = "testinguser";
$password = "katlina@test123";

For PHP 7:

if (strpos(strtolower($password), strtolower($username)) === false || passContainsName($name, $password)) {
    echo 'password not valid in PHP 7'.PHP_EOL;
 }
 
 
 function passContainsName($name, $password){
     foreach (explode(" ", $name) as $toCheck) {
         if (strpos(strtolower($password), strtolower($toCheck)) === false) {
            return true;
         }
     }
     return false;
 }

For PHP 8:

if (str_contains(strtolower($password), strtolower($username)) || passContainsName($name,$password)) {
 echo 'password not valid';
 }
 
 
 function passContainsName($name, $password){
     foreach (explode(" ", $name) as $toCheck) {
         if (str_contains(strtolower($password), strtolower($toCheck))) {
            return true;
         }
     }
     return false;
 }

fiddle [here] with php 7 and 8 examples1

Voxxii
  • 369
  • 2
  • 9