PHP -> REGEX | password validation not working - php

I use this (almost) complex password verification:
function is_password($password) {
return preg_match("^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20}$", $password);
}
So it must contain:
one digit from 0-9,
one lowercase character,
one uppercase character,
at least 6 characters
at most 20 characters
This does not seem to work. Whenever I type certain characters like e, t, o, j, c and b; the function returns true if allowed length is correct. So uppercase and digit is not being validated..
What am I doing wrong?

You forgot to use delimiters. Use this code instead:
return preg_match("/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20}$/", $password);
Or you may split each condition and use this code:
return mb_strlen($password)>=6 && mb_strlen($password)<=20
&& preg_match("/[a-z]+/", $password) && preg_match("/[A-Z]+/", $password)
&& preg_match("/[0-9]+/", $password);

I would break this apart into multiple checks. This will allow you to intelligently give feedback to the user (or to a log) as to why the password selection failed.
<?php
function is_password($password){
if (strlen($password) < 6) {
// too short
return false;
}
if (strlen($password) > 20) {
// too long
return false;
}
if (!preg_match("/[A-Z]/", $password) {
// no upper
return false;
}
if (!preg_match("/[a-z]/", $password) {
// no lower
return false;
}
if (!preg_match("/[0-9]/", $password) {
// no digit
return false;
}
return true;
}
?>

Related

How to remove everything but allow letter, number and underscore?

How to remove everything but allow letter, number and underscore only in my validation for the username? I tried this code but it allows space:
function customUsername($username)
{
if (!preg_match('/^[a-z.,\-]+$/i',$username))
{
$this->form_validation->set_message('customUsername', 'The username field');
}
}
Use the following regex
function customUsername($username)
{
if (!preg_match('/^[a-zA-Z0-9_]+$/i',$username))
{
$this->form_validation->set_message('customUsername', 'The username field');
}
}
You can use ASCII code of every letter, number and underscore.
follow this link for ASCII code http://ascii.cl/ .
jQuery is like this.
$('#keyId').keydown(function(e){
var key = e.charCode || e.keyCode || 0;
return (
key == 8 ||
(key >= 23 && key <= 105)
);
});
So Simple It allow only Alphanumeric and Underscore only
<?php
$str='fdfdf5_';
if(preg_match('/^[a-zA-Z0-9_]+$/',$str))
{
echo "success";
}
else
{
echo "failed";
}
?>

Disabling some characters with preg_match

I'm having an issue with my register page, i noticed that people can register with alt codes like this "ªµµª" and i tried to fix it by using preg_replace but when i did that i couldn't register anymore, atleast not with the worldwide alphabet
final public function validName($username)
{
if(strlen($username) <= 25 && ctype_alnum($username))
{
return true;
}
return false;
}
Tried to fix it by replacing it with this
if(strlen($username) <= 25 && preg_match("/[^a-zA-Z0-9]+/", $username))
But i'm obviously doing something wrong...
Apparently, you are confusing two different uses of the caret (^) metacharacter.
Indeed, it may be two things in a regular expression:
It may assert the start of the subject, which is what you probably want.
It may negate the class, which is what you're doing in your code.
Source: http://php.net/manual/en/regexp.reference.meta.php
Here is a modified version of your code, with the caret (^) and dollar ($) signs to assert the start and the end of the strings you're analyzing:
function validName($username)
{
if (strlen($username) <= 25 && preg_match("/^[a-zA-Z0-9]+$/", $username))
{
return true;
}
return false;
}
$names = array(
'Abc1',
'Abc$',
"ªµµª"
);
foreach ($names as $name) {
echo "<br>" . $name . ': ' . (validName($name) ? 'valid' : 'invalid');
}
// -- Returns:
// Abc1: valid
// Abc$: invalid
// ªµµª: invalid
Note that you may reduce the code inside your function to one line:
function validName($username)
{
return strlen($username) <= 25 && preg_match("/^[a-zA-Z0-9]+$/", $username);
}

Validate password policy with PHP preg_match

I'm trying to validate a password using preg_match and RegEx but it doesn't seem to work. What I want to do is: ensure the password meets the following minimal conditions:
- Contains mixed case letters
- Contains atleast one number
- The rest can be anything as long as the two conditions above are met.
I've tried the following RegEx but it doesn't seem to work properly:
(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])
I've had other previous easier RegEx'es like: [A-Za-z0-9] but without success. I'm checking if preg_match($string, $pattern) == 0 (meaning the pattern doesn't match => validation fails) but it always returns 0. What am I doing wrong ?
Just add a starting anchor to your regex,
^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])
OR
^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9]).*
Example:
$yourstring = 'Ab';
$regex = '~^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])~m';
if (preg_match($regex, $yourstring)) {
echo 'Yes! It matches!';
}
else {
echo 'No, it fails';
} // No, it fails
I always try to avoid regex if it's possible so I took a different approach to the problem. The below code will test the password for at least one uppercase, one lowercase and one digit.
function isValidPassword($password)
{
$hasUppercase = false;
$hasLowercase = false;
$hasDigit = false;
foreach (str_split($password) as $char)
{
$charAsciiValue = ord($char);
if ($charAsciiValue >= ord('A') && $charAsciiValue <= ord('Z')) {
$hasUppercase = true;
}
if ($charAsciiValue >= ord('a') && $charAsciiValue <= ord('z')) {
$hasLowercase = true;
}
if ($charAsciiValue >= ord('0') && $charAsciiValue <= ord('9')) {
$hasDigit = true;
}
}
return $hasUppercase && $hasLowercase && $hasDigit;
}
var_dump(isValidPassword('Ab9c'));
var_dump(isValidPassword('abc'));
Output
bool(true)
bool(false)
I offer a different solution, mainly because regexp provides little error reporting, and you would have to manually test the string afterwards anywhay for cohesion. Consider breaking the patterns apart and adding their own error. Iterate each of the requirements, and test the pattern. Push errors into an array and check after for their existence. Return a predeclared variable as true/false for the purpose of validating using if(validate_password($pass)):. Here's the mockup:
function validate_password($pass){
$requirements = array();
//uppercase
$requirements['uppercase']['pattern'] = '/[A-Z]/';
$requirements['uppercase']['error'] = 'Your password must contain at least one uppercase letter.';
//lowercase
$requirements['lowercase']['pattern'] = '/[a-z]/';
$requirements['lowercase']['error'] = 'Your password must contain at least one lowercase letter.';
//requires a number
$requirements['number']['pattern'] = '/[0-9]/';
$requirements['number']['error'] = 'Your password must contain at least one number.';
//special characters
$requirements['special_character']['pattern'] = '/[!##$%^&*()\\-_=+{};\:,<\.>]/';
$requirements['special_character']['error'] = 'Your password must contain at least one special character.';
//length
$requirements['length']['pattern'] = '/^.{8,}/';
$requirements['length']['error'] = 'Your password must be at least 8 characters in length total.';
$is_valid = false; //our flag to return as true once all tests have passed.
$errors = false;
//validate all requirements
foreach($requirements as $idx => $req):
if(preg_match($req['pattern'], $pass, $matches)):
$is_valid = true;
else:
$errors[] = $req['error'];
$is_valid = false;
endif;
endforeach;
//if we had errors above
if($errors):
$is_valid = false;
foreach($errors as $error):
echo '<p>', $error, '</p>';
endforeach;
endif;
return $is_valid;
}
$pass = 'j!Adz6'; //change this to test
echo validate_password($pass);
And an eval.in example for your pleasure.

check if numeric php

my problem is, i have a form which i fill blabla and after i submit i need to check if the var '$number' contains only 9 numbers. which means that if it contains at least 1 letter or has less or more than 9 length it should return false, else it should return true;
this is what i got so far:
if (!is_numeric ($number) {
//do
} else {
}
1st problem: This code should take care of the only numbers part but it doesnt, it always returns false.
2nd: do you guys know of any way to take care of the 9 digits only verification?
thanks and sorry for my bad english, not my native language :P
Your number may contain unwanted whitespaces which cause the is_numeric() test not to work properly
So do the following: $number = trim($number); to remove them.
Then indeed this snippet is good to check if your variable is a number:
if (!is_numeric ($number)) {
//do
} else {
}
And for the number digits do a if statement to see if your number is between 100000000 and 999999999
So the full code will be:
$number = trim($number);
if (!is_numeric ($number)) {
//do
} else {
if ($number >= 100000000 && $number <= 999999999) {
// Everything is ok
} else {
}
}
Didn't understood your complete question coz of you native language :p, but i think you want this:
if (is_numeric($number) {
if(strlen($number) == 9){
return true;
} else {
return false;
}
} else {
echo 'Not a number';
}
Check if it contains digits and check whether its exactly contains 9.
$number = '123456789';
if(!preg_match('/^\d{9}$/', $number)) {
echo 'not ok';
} else {
echo 'ok';
}

If statement to check the number of characters in a textbox

when the user adds a contact, it checks to see if the "character" count is 8, then it check the database to see if the username and the NewContact already exist, and if it "false", it inserts the new contact.
the bit that doesn't work is limiting the number of characters to 8
if (intval($s_id) == 8)
{
$db = mysql_connect("at-web2.xxx", "user_xxx", "xxxx");
mysql_select_db("db_xxx",$db);
$result = mysql_query("SELECT * FROM contacts WHERE u_id='$username' and c_id='$s_id'",$db);
$myrow = mysql_fetch_row($result);
if(!$myrow)
{
mysql_query("INSERT INTO contacts(u_id, c_id) VALUES ('$username','$s_id')",$db);
header("Contact Added");
}
else
{
header("Contact Already Exist");
}
}
else
{
header("Incomplete Contact");
}
You need strlen function.
if(strlen($s_id) == 8)
you have to use strlen to get number of characters
if (intval($s_id) == 8)
should be
if (strlen($s_id) == 8)
Try to use strlen with trim function to get accurate length of string.
if(strlen(trim($s_id)) == 8)
Use strlen (stringlength) predefined php function for getting the exact length of the string .
if(strlen($string) == 8)
{
//Statements
}
else
{
//statements
}

Categories