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';
}
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';
}
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
Related
For my website i want to have registration. And everything goes well until it's time for validation. So, i have to this all in different files (validation in validation.php, registration in registration.php and registration form in registrationForm.php). In registration.php i have something like this:
<?php
session_start();
include 'validation.php';
include "mail.php";
include 'dbConnection/dbconn.php';
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$surname = $_POST['surname'];
$username = $_POST['username'];
$password1 = $_POST['password1'];
$password2 = $_POST['password2'];
$email = $_POST['email'];
//sendMail("test", "test");
if (validateName($name) && validateSurname($surname) && validateEmail($email) && validatePassword($password1) && validateUsername($username) && checkIfPasswordsAreMatching($password1, $password2)) {
echo "Worked";
} else {
echo "Not worked";
header("Location: registrationForm.php");
}
} else {
header("Location: registrationForm.php");
}
?>
And my problem is that no matter if i put good data or completely wrong data my validation always says that it's wrong.
Here is my validation code (validation.php):
<?php
session_start();
$allChecked = true;
function validateName($string) {
if (strlen($string) < 2) {
$allChecked = false;
$_SESSION['nameError'] = "Your name is too short. It has to be at least 2 characters long.";
}
if (preg_match('[\W]', $string)) {
$allChecked = false;
$_SESSION['nameError'] = "Your name cannot contain any special character.";
}
return $string;
}
function validatePassword($string) {
if (strlen($string) < 8 || strlen($string) > 20) {
$allChecked = false;
$_SESSION['passwordError'] = "Your password must be between 8 and 20 characters long.";
}
if (preg_match('/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]/', $string) == false) {
$allChecked = false;
$_SESSION['passwordError'] = "Your password must contain at least 1 big letter, 1 special character, 1 number and 1 small letter.";
}
return $string;
}
function validateSurname($string) {
if (strlen($string) < 2) {
$allChecked = false;
$_SESSION['surnameError'] = "Your surname is too short. It has to be at least 2 characters long.";
}
if (preg_match('[\W]', $string)) {
$allChecked = false;
$_SESSION['surnameError'] = "Your surname cannot contain any special character.";
}
return $string;
}
function validateUsername($string) {
if (strlen($string) < 2 || strlen($string) > 20) {
$allChecked = false;
$_SESSION['usernameError'] = "Your username must be between 2 and 20 characters";
}
/*
$sql = "SELECT * FROM Users WHERE username = '$string'";
$sql = $conn->query($sql);
$nameExists = $result->fetch();
if($nameExists) {
$allChecked = false;
$_SESSION['usernameError'] = "Name is already taken";
}
*/
return $string;
}
function validateEmail($string) {
$em = filter_var($string, FILTER_VALIDATE_EMAIL);
if (!$em){
$allChecked = false;
$_SESSION['emailError'] = "Your email has to be valid.";
}
/*
$sql = "SELECT * FROM Users WHERE mail = '$string'";
$result = $conn->query($sql);
$emailExists = $result->fetch();
if($emailExists) {
$allChecked = false;
$_SESSION['emailError'] = "Email is already taken";
}
*/
return $allChecked;
}
function checkIfPasswordsAreMatching($password1, $password2) {
if ($password2 != $password1) {
$allChecked = false;
$_SESSION['passwordError'] = "Passwords must be the same";
}
return $allChecked;
}
?>
In each of your return statements check $allChecked and if it has NOT been set return true instead of $allChecked.
return (isset($allChecked) ? $allChecked : true);
In your functions validateName, validateSurname, validatePassword, validateUsername you are returning the original string instead of validation result. In validateEmail and checkIfPasswordsAreMatching you are returning $allChecked but it's not initialized with value if all checks are passed so null is returned instead.
You should rewrite your validation functions to look like this
function validateName($string) {
if (strlen($string) < 2) {
$_SESSION['nameError'] = "Your name is too short. It has to be at least 2 characters long.";
return false;
}
if (preg_match('[\W]', $string)) {
$_SESSION['nameError'] = "Your name cannot contain any special character.";
return false;
}
return true;
}
I'm working on a log in form that users a text file (users.txt) to validate username/password against. I cannot use MYSQL for this.
The text file records are in this format:
user one:user1#email.com:user1:password1
user two:user2#email.com:user2:password2
If it validate just the USERNAME only, then it successfully checks the user: if ($currUser == $userUsername) {$valid = true; break;}BUT if I then try to validate both username and password I get the wrong result.($currUser == $userUsername && $currPass == $userPass) {$valid = true; break;} Results in "Invalid username or password"
I can't figure out what I'm doing wrong? When I echo the username and passwords they are a match!!!
SCRIPT:
if(isset($_POST['submit'])){
$form_is_submitted = true;
//FORM PROCESSING
if(isset($_POST['userName']) && isset($_POST['password'])) {
$currUser = $_POST['userName'];
$currPass = $_POST['password'];
$valid = false;//flag
while (!feof($fileHandle)) {
$userRow = fgets($fileHandle);
$userDetails = explode(':', $userRow);
if (!isset($userDetails[2])) {
$userDetails[2] = null;
}
if (!isset($userDetails[3])) {
$userDetails[3] = null;
}
$userUsername = $userDetails[2];
$userPass = $userDetails[3];
if ($currUser == $userUsername /*&& $currPass == $userPass*/) {
$valid = true;
//break;
}
}
if ($valid) {
echo "<br> $userUsername logged in sucessfully<br>";
} else {
echo "<br>Invalid user name or password<br>";
//FOR DEGUGGING ONLY!
echo $currUser . $userUsername;
echo $currPass . $userPass;
echo $_POST['password'];
echo $_POST['userName'];
}
} else {
$errors_detected = true;
$errors['not set'] = "Please enter username and password";
}
}
the fgets() function returns a line INCLUDING the linefeed \n (and the carriage return \r if its there). that means you have to remove those.
just change this:
$userPass = $userDetails[3];
to this:
$userPass = trim($userDetails[3]);
and it should work
I'am newbie with PHP and i have a issue with my php form validation that return this error, if the username and the password are not defined.
Notice: Undefined variable: username in D:\hpsp\controller\loginvalidation.inc.php on line 64
I use 2 functions (usernameValidation & passwordValidation) to check if $_POST input are correct or not but i don't know what's and where i have to put the correct script, Thank you in advance.
<?php
session_start();
require_once('../model/pdo.inc.php');
// function for checking the username validation (not empty & Regex)
function usernameValidation($username) // Username as parameter
{
if ( !empty($_POST['username']) )
{
$username = strtolower(htmlspecialchars($_POST['username'])); // username will be tranform to lowercase before regex matching
if ( preg_match('#^[a-z0-9\.]{5,20}$#', $username) ) // 5 <= username lenght <= 20 in lowercase character to be valid
{
return true; // return true when the username is valid
}
else
{
echo "Invalid username, please re-try" ;
}
}
else
{
echo "Enter your username";
}
}
// function for checking the password validation (not empty & Regex)
function passwordValidation($password) // Password as parameter
{
if ( !empty($_POST['password']) )
{
$password = htmlspecialchars($_POST['password']) ; // Protect the password
if ( preg_match('#^[a-zA-Z0-9\.-_#$()]{6,10}$#', $password) ) // 6 <= password length <= 10 character to be valid
{
return true; // return true when password is valid
}
else
{
echo "Invalid password, please re-try";
}
}
else
{
echo "Enter your password";
}
}
if ( usernameValidation($username) == true AND passwordValidation($password) == true )
{
// PDO Query (SELECT ...)
}
I would do something like this (note you never want to echo out individual messages for email and password to stop hackers gaining information about which is correct:
session_start();
require_once('../model/pdo.inc.php');
//username and password will contain the posted resulte or FALSE
$username = usernameValidation();
$password = passwordValidation();
if (!$username OR !$password) {
echo 'Invalid username or password!';
die;
}
// PDO Query (SELECT ...)
// function for checking the username validation (not empty & Regex)
function usernameValidation() { // Username as parameter
if (!empty($_POST['username'])) {
$username = strtolower(htmlspecialchars($_POST['username'])); // username will be tranform to lowercase before regex matching
if (preg_match('#^[a-z0-9\.]{5,20}$#', $username)) { // 5 <= username lenght <= 20 in lowercase character to be valid
return $username; // return true when the username is valid
}
}
return FALSE;
}
// function for checking the password validation (not empty & Regex)
function passwordValidation() { // Password as parameter
if (!empty($_POST['password'])) {
$password = htmlspecialchars($_POST['password']); // Protect the password
if (preg_match('#^[a-zA-Z0-9\.-_#$()]{6,10}$#', $password)) { // 6 <= password length <= 10 character to be valid
return $password; // return true when password is valid
}
}
return FALSE;
}
Define your functions withow arguments
function usernameValidation(){ ... }
and call it
if ( usernameValidation() == true AND passwordValidation() == true )
<?php
session_start();
require_once('../model/pdo.inc.php');
// function for checking the username validation (not empty & Regex)
function usernameValidation($username) // Username as parameter
{
if ( !empty($_POST['username']) )
{
$username = strtolower(htmlspecialchars($_POST['username'])); // username will be tranform to lowercase before regex matching
if ( preg_match('#^[a-z0-9\.]{5,20}$#', $username) ) // 5 <= username lenght <= 20 in lowercase character to be valid
{
return true; // return true when the username is valid
}
else
{
echo "Invalid username, please re-try" ;
}
}
else
{
echo "Enter your username";
}
}
// function for checking the password validation (not empty & Regex)
function passwordValidation($password) // Password as parameter
{
if ( !empty($_POST['password']) )
{
$password = htmlspecialchars($_POST['password']) ; // Protect the password
if ( preg_match('#^[a-zA-Z0-9\.-_#$()]{6,10}$#', $password) ) // 6 <= password length <= 10 character to be valid
{
return true; // return true when password is valid
}
else
{
echo "Invalid password, please re-try";
}
}
else
{
echo "Enter your password";
}
}
$username = $_POST['username'];
$password = $_POST['password'];
if ( usernameValidation($username) == true AND passwordValidation($password) == true )
{
// PDO Query (SELECT ...)
}
Change your last if condition to the code below:
if ( usernameValidation($_POST['username']) == true AND passwordValidation($_POST['password']) == true )
{
}
In your functions only use the variables $username and $password and not(!) $_POST['username'] and $_POST['password']
you are defined $username and $password, it is $_POST['username'] and $_POST['password']. And you can also make function without parameter. by making these change your problem will solved.
I have this PHP code which should return only either true or false after running multiple stored functions, but unfortunately it does not work as expected.
I firstly check the email validation and return true if valid and false if invalid, then i am doing the same for username.
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Email is valid
if(checkmail($_POST['email'])) {
$_SESSION['v_mail'] = $_POST['email'];
$valid = true;} else { $valid=false; }
// username is valid
if(checkuser($_POST['username'],5,10)) {
$_SESSION['v_username'] = $_POST['username'];
$valid=true;} else { $valid=false; }
}
I need to return only False or True after checking both.
I know that it is very small trick but i could not get it.
Try this:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Email is valid
if(checkmail($_POST['email'])) {
$_SESSION['v_mail'] = $_POST['email'];
$valid = true;} else { $valid=false; }
// username is valid
if(checkuser($_POST['username'],5,10)) {
$_SESSION['v_username'] = $_POST['username'];
} else { $valid=false; } //and between the last $valid value
}
or again this:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Email is valid
if(checkmail($_POST['email'])) {
$_SESSION['v_mail'] = $_POST['email'];
$valid = true;} else {
$valid=false; return} //exit from the function if valid is false
// username is valid
if(checkuser($_POST['username'],5,10)) {
$_SESSION['v_username'] = $_POST['username'];
$valid=true;} else { $valid=false; }
}
if(checkmail($_POST['email']) && checkuser($_POST['username'],5,10)) {
$_SESSION['v_mail'] = $_POST['email'];
$_SESSION['v_username'] = $_POST['username'];
$valid = true;
} else {
$valid = false;
}
Sorry was tired missed part of the code, however I would approach this problem little bit differently:
$isMail = (checkmail($_POST['email'])) ? $_SESSION['v_mail'] = $_POST['email'] : false;
$isUser = (checkuser($_POST['username'],5,10)) ? $_SESSION['v_username'] = $_POST['username'] : false;
$valid = $isMail && $isUser;
Or move $_SESSION variables to checkmail, checkuser functions and then simply $valid = checkmail($_POST['email']) && checkuser($_POST['username'],5,10)
hi i created this code below in my wordpress theme within my login.php page i created conditional statements successfully without any problem but in my last if statement when the username and password is correct i can't when this statement is correct i log in?
i want when the username and password is correct directly show legge in username and add the log out link to log out from the theme.
<?php
$error = '';
$success = '';
global $user_identity;
if(isset($_POST['task']) && $_POST['task'] == 'login') {
$username = esc_attr($_POST['login_username']);
$password = esc_attr($_POST['login_password']);
$remember = esc_attr($_POST['login_remember']);
$user = get_user_by('login', $username);
$user_id = $user->ID;
$user_data = get_userdata($user_id);
$user_login = $user_data->user_login;
$user_pass = $user_data->user_pass;
if($username == '' && $password == '') {
$error = 'Please Fill Required Fields!';
}
if($username == '') {
$error = 'Please Enter Your Username';
}
if($password == '') {
$error = 'Please Enter Your Password';
}
if($user_login != $username) {
$error = 'The Username is Incorrect';
}
if($user_pass != $password) {
$error = 'The Password is Incorrect';
}
if($user_login == $username && $user_pass == $password) {
}
}
?>
hey just create array of user data and passed into wp_signon($data,false) see below.
$login_data = array();
$login_data['user_login'] = $username;
$login_data['user_password'] = $password;
$login_data['remember'] = $remember; // set true or false for remember
$user_verify = wp_signon( $login_data, false );
if ( is_wp_error($user_verify) )
{
echo $user->get_error_message();
exit;
} else {
header("Location: " . home_url() . "/login/error/");
}
read document for more detail wp_signon()