0

How can I limit the user so that his password should not contain his name/user/e-mail?

This is the validation script that I use at the moment:

<?php
    $register = $_POST['register'];
    if (isset ($register))
    {
        $email = mysql_real_escape_string($_POST['email']);
        $username = mysql_real_escape_string($_POST['username']);
        $password = sha1(md5(mysql_real_escape_string($_POST['password'])));
        $repeat_password = sha1(md5(mysql_real_escape_string($_POST['repeat_password'])));
        $first_name = mysql_real_escape_string($_POST['first_name']);
        $last_name = mysql_real_escape_string($_POST['last_name']);
        $birthday = mysql_real_escape_string($_POST['birthday']);
        $sex = mysql_real_escape_string($_POST['sex']);
        $registered = date("Y-m-d H:i:s"); 

        // Form validation

        // Password validation
        $password  = $_POST["password"];
        $uppercase = preg_match('@[A-Z]@', $password);
        $lowercase = preg_match('@[a-z]@', $password);
        $number    = preg_match('@[0-9]@', $password);
        $length    = preg_match("@^.{8,}$@" , $password);

        if(!$uppercase || !$lowercase || !$number ||  !$length  ) {
           echo "Parola trebuie sa aiba min 8 caractere si sa contina cel putin o litera mare, o litera mica si o cifra.";
        }


        // Password = Password validation
        elseif ($_POST['password'] != $_POST['repeat_password'])
        {
            echo "Parolele nu corespund.";
        }

        // E-mail address format
        elseif (!filter_var($email,FILTER_VALIDATE_EMAIL))
        {
            echo "Formatul adresei de email este invalid.";
        }

        // No e-mail typed
        elseif (empty($_POST['email']))
        {
            echo "Nu ati completat adresa de email.";
        }

        // No username typed
        elseif (empty($_POST['username']))
        {
            echo "Nu ati completat numele de utilizator dorit.";
        }

        // No password or password validation typed
        elseif ((empty($_POST['password']) or empty($_POST['repeat_password'])))
        {
            echo "Parola trebuie introdusa in ambele campuri.";
        }

        // MySQL validations
        else
        {
            require_once("db_connect.php");


            $query_email="SELECT email FROM users WHERE email='$email'";
            $result_email=mysql_query($query_email) or die (mysql_error());

            $query_username="SELECT username FROM users WHERE username='$username'";
            $result_username=mysql_query($query_username) or die (mysql_error());



            // Check if e-mail exists
            if (mysql_num_rows($result_email)>0)
            {
                echo "Email-ul introdus a mai fost inregistrat.";
            }

            // Check if user exists

            elseif (mysql_num_rows($result_username)>0)
            {
                echo "Username-ul introdus a mai fost inregistrat. Va rugam sa va alegeti alt username.";
            }

            // Add new user to database
            else
            {
                $query="INSERT INTO users VALUES ('', '$username', '$password', '$email', '$first_name', '$last_name', '$birthday', '$sex', '', '$registered', '')";
                mysql_query($query) or die (mysql_error());
                echo "Cont creat cu succes!";

                // Send E-mail
                $to = $_POST['email'];
                $subject = "Contul meu";
                $message = "Contul dumneavoastra a fost creat cu succes! Date contului sunt: ";
                $from = "someonelse@example.com";
                $headers = "From:" . $from;
                mail($to,$subject,$message,$headers);
            }

        }
    }   
?>

I know that MySQL is depreciated. I'll switch to MySQLi ASAP and adapt the script so that it won't be SQL Injection vulnerable. The echoed messages are in romanian. I guess you don't need them translated. Just ignore them.

Since I don't have an e-mail server please check out the "Send E-mail" part as well and let me know if it would work, it's the first time that I use it.

Let me know before downrating so that I can edit my question. Thanks!

SporeDev
  • 608
  • 1
  • 8
  • 26
  • You could use the `strpos()` function. http://php.net/manual/en/function.strpos.php Also mail will only work if you have an SMTP server available. – Ben Fortune Sep 12 '13 at 10:06

5 Answers5

1

Have a look at the function strpos

http://php.net/manual/en/function.strpos.php

Thomas
  • 397
  • 6
  • 13
  • Welcome to SO! Answers that are just links are discouraged here. There are two main reasons for this: it's usually much more helpful to answer users' specific issues directly, and even links to good resources sometimes go bad. Please see [this meta post](http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers) for more detail. – Pops Sep 19 '13 at 01:17
1

you could simple use strstr or strpos to determine, if the password contains name, email or username.

Instead of using the mail function, you should use phpmailer: https://github.com/PHPMailer/PHPMailer It is as easy to use, but uses an external smtp-server. Using the php mail() function without a well configured local smtp, will end in all your mails beeing treaded as junk mail.

dognose
  • 20,360
  • 9
  • 61
  • 107
  • Thank you very much for the information regarding the mail function. I find the link you gave me quite informative. I'll have a look after I adapt my code to use MySQLi since that's a priority. – SporeDev Sep 12 '13 at 10:13
1

Use strpos() or preg_match().

Example using strpos() with username and password :

if ( (strpos($password,$_POST['username']) !== false ) || ( strpos($password,$_POST['password'] ) !== false ) ) {
    echo 'password not valid';
}

Example using preg_match():

<?php
$password='username email name jaja ';
$username='username';
$email='email';
$name='name';

if (preg_match("#(($email)|($username)|($name))#", $password))
    echo 'probleme';
else echo 'no problem';
?>

If you want to match both upper and lower case letters :

stripos() : Find the position of the first occurrence of a case-insensitive substring in a string

For preg_match() , add i (Docs here) modifier after last # like this :

preg_match("#(($email)|($username)|($name))#i", $password)

NOTE : the documentation says "Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster."

Community
  • 1
  • 1
Charaf JRA
  • 8,249
  • 1
  • 34
  • 44
  • You saved the day again. Thank you! – SporeDev Sep 12 '13 at 10:14
  • added solution using preg_match – Charaf JRA Sep 12 '13 at 10:20
  • Can I add multiple parameters in the condition (the one that uses strpos)? So that I have a single condition checking if there's also an e-mail address or name in the password as well. – SporeDev Sep 12 '13 at 10:21
  • @SporeDev I've provided an answer that takes a unlimited array of arguments. – Matt Harrison Sep 12 '13 at 10:22
  • I get this error: Warning: preg_match(): Unknown modifier 'y' in C:\xampp\htdocs\Signup\includes\signup.php on line 40 This is my code (elseif being line 40) elseif (preg_match("@(($email)|($username)|($first_name))@", $password)) { echo 'Parola nu poate sa contina username-ul, email-ul sau numele dumneavoastra.'; } – SporeDev Sep 12 '13 at 10:51
  • where is **y** in this lines ?? check your code , it something outside this statements – Charaf JRA Sep 12 '13 at 11:01
  • That's what I'm wondering as well. I used Ctrl+f to see every "y" in the document and the only ones that I get are part of MySQL, $query or $birthday. No "y" on it's own anywhere. – SporeDev Sep 12 '13 at 11:04
  • I found this question but I don't know if it's the same problem that I have. http://stackoverflow.com/questions/5589807/preg-match-unknown-modifier Nevermind. Turns up that's not the problem. Still can't find it thou. – SporeDev Sep 12 '13 at 11:06
  • I see what's wrong , the problem is that email contains **@** and preg_match contains @ as well , replace @ in preg_match by **#** or a special caracter that can't be in your variables values, read the last Note i added to my answer – Charaf JRA Sep 12 '13 at 11:19
  • For some reason the passwords now don't get their encryption in sha1 and md5. They appear in the database as they are typed. – SporeDev Sep 12 '13 at 11:46
1

use strstr or strpos to determine, if the password contains name, email or username.

example:

if (strpos($password,$_POST['username']) !== false) {
    echo 'Username found in the password';
}
1

In the spirit of reusable code, I've created a function called stringContainsOneOf that simply takes a string and an array of strings and checks if that first string contains any of the array elements.

//User's information
$email = "joe.smith@gmail.com";
$username = "joesmith";
$name = "Joe Smith";

//Validation function
function stringContainsOneOf($string, $checkArray)
{
    foreach($checkArray as $element)
        if(strpos(strtolower($string), strtolower($element)) !== false)
            return true;

    return false;
}

//Usage example
var_dump(stringContainsOneOf("mysecretpassword", array($email, $username, $name))); //returns false
var_dump(stringContainsOneOf("joesmithspassword", array($email, $username, $name))); //returns true
Matt Harrison
  • 13,381
  • 6
  • 48
  • 66