I am getting a logical error I believe I am using PHP as my server side language and I am performing password checks. Users will not be allowed to enter a password less than 8 characters and no more than 32 characters.
register.php
<?php $pageTitle = "Register"; ?>
<?php $sectoin = "signing"; ?>
<?php include 'INC/header.php'; ?>
<?php
$submit = $_POST['submit'];
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$repeatPassword = strip_tags($_POST['repeatPassword']);
$email = strip_tags($_POST['email']);
$date = date("m-d-Y");
if ($submit) {
// Checking for exsistence
if ($username && $password && repeatPassword && $email) {
// Encrypts the Pasword
$password = md5($password);
$repeatPassword = md5($repeatPassword);
// Do Passwords Match
if ($password == $repeatPassword) {
// Check Character Length of Username
if (strlen($username) > 16 || strlen($username) <= 2) {
echo "<h3 class='text-center'> <span class='alert alert-warning'> Your <b>Username</b> must be between 3 and 16 characters! </h3> </span>";
} else {
// Check Password Length
if (strlen($password && $repeatPassword) < 8) {
echo "<h3 class='text-center'> <span class='alert alert-warning'> Your <b>Password</b> is less than 8 characters! </h3> </span>";
} else {
echo 'Registration Completed!';
}
}
} else echo "<h3 class='text-center'> <span class='alert alert-danger'> Your <b>Passwords</b> must match! </h3> </span>";
} else echo "<h3 class='text-center'> <span class='alert alert-warning'> Please fill out <b>All</b> fields!</h3> </span>";
}
?>
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-body">
<div class="page-header">
<h3 class="text-center"> Registration </h3>
</div>
<form class="form-horizontal" role="form" action="register.php" method="POST">
<!--Start of Username-->
<div class="form-group">
<label for="username" class="col-sm-2 control-label"> Username </label>
<div class="col-sm-10">
<div class="input-group">
<span class="input-group-addon"> <span class="glyphicon glyphicon-user"> </span> </span>
<input type="text" name="username" class="form-control" id="username" placeholder="Username" />
</div>
</div>
</div>
<!--End of Username-->
<!--Start of E-Mail-->
<div class="form-group">
<label for="email" class="col-sm-2 control-label"> E-Mail </label>
<div class="col-sm-10">
<div class="input-group">
<span class="input-group-addon"> <span class="glyphicon glyphicon-envelope"> </span> </span>
<input type="email" name="email" class="form-control" id="email" placeholder="E-Mail" />
</div>
</div>
</div>
<!--End of E-Mail-->
<!--Start of Password-->
<div class="form-group">
<label for="password" class="col-sm-2 control-label"> Password </label>
<div class="col-sm-10">
<div class="input-group">
<span class="input-group-addon"> <span class="glyphicon glyphicon-star"> </span> </span>
<input type="password" name="password" class="form-control" id="password" placeholder="Password" />
</div>
</div>
</div>
<!--End of Password-->
<!--Start of Repeat Password-->
<div class="form-group">
<label for="repeatPassword" class="col-sm-2 control-label"> <span id="repeatPassword"> Repeat Password </span> </label>
<div class="col-sm-10">
<div class="input-group">
<span class="input-group-addon"> <span class="glyphicon glyphicon-check"> </span> </span>
<input type="password" name="repeatPassword" class="form-control" id="password" placeholder="Password" />
</div>
</div>
<!--End of Repeat Password-->
<!--Start of Checkbox and Submit Button-->
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<label class="checkbox">
<input type="checkbox" name="rememberMe" value="rememberMe" id="rememberMe"> <span id="rememberUs"> Remember Me </span>
</label>
<button type="submit" name="submit" value="Register" class="btn btn-primary slideToTheLeft"> Register </button>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="col-sm-2"></div>
</div>
<?php include 'INC/footer.php'; ?>
If I take the '&& $repeatPassword' out of the equation it skips the condition and echos.
if (strlen($password && $repeatPassword) < 8 {
However, it is called that $repeatPassword = $password, so I shouldn't even need the '&& repeatPassword' but it won't do anything if it is included into the code.
However, the main problem besides that is that no matter what the if statement is stating that no matter what the password is less than 8 characters.
As a means of testing if supplied values are within permitted bounds you could try:
$valid_username=in_array( strlen( $username ), range(2,16) );
$valid_password=$password===$repeatPassword && in_array( strlen( $password ), range(8,32) );
if( $valid_username && $valid_password ){/* all good */}
example:
if( $submit ) {
if( $username && $password && $repeatPassword && $email ) {
// hash the Passwords
$password = md5( trim( $password ) );
$repeatPassword = md5( trim( $repeatPassword ) );
$unrange=range(3,16);
$pwdrange=range(8,32);
$valid = true;
$valid_username = in_array( strlen( $username ), $unrange );
$valid_password = in_array( strlen( $password ), $pwdrange );
$password_match = $password===$repeatPassword;
if( !$valid_password ){
$valid=false;
echo "<h3 class='text-center'> <span class='alert alert-warning'> Your <b>Password</b> should be between ".min( $pwdrange )." and ".max( $pwdrange )." characters! </h3> </span>";
}
if( !$valid_username ){
$valid=false;
echo "<h3 class='text-center'> <span class='alert alert-warning'> Your <b>Username</b> must be between ".min( $unrange )." and ".max( $unrange )." characters! </h3> </span>";
}
if( !$password_match ){
$valid=false;
echo "<h3 class='text-center'> <span class='alert alert-danger'> Your <b>Passwords</b> must match! </h3> </span>";
}
if( $valid ) {
echo 'Registration Completed!';
/* add to db? */
}
} else echo "<h3 class='text-center'> <span class='alert alert-warning'> Please fill out <b>All</b> fields!</h3> </span>";
}
You probably don't need to check the length of both $password and $repeatPassword since you will also be checking to see if they match each other.
if (strlen($password < 8) {
// error
} elseif ($password != $repeatPassword) {
// error
} else {
// ALL IS GOOD !
}
I had actually solved my problem, I decided to take out the or to the password and it had solved the problem and everything is up and running.
Try this:
if (strlen($password) >= 8 && strlen($password) <= 32) {
if (strlen($repeatpassword) >= 8 && strlen($repeatpassword) <= 32) {
// code here
}
}
I think it's a bit odd to check both passwords, however.
So, my solution would be:
if (strlen($password) >= 8 && strlen($password) <= 32) {
// code here
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Help. Im trying to do validation for the registration code with PHP but it doesn't displayed.
here is my code for the registration form (register.php):
here is the validation, I write it before the
<?php
$name_error = "";
$pass_error = "";
$email_error = "";
$pass_error = "";
$pass2_error = "";
//validation
if(isset($_POST['register'])) {
if(empty($_POST["first-name"] || $_POST["last-name"])) {
$name_error = "Please enter your name.";
}
if(empty($_POST['email'])) {
$email_error = "Please enter the email";
}
if(empty($_POST['password'])) {
$pass_error = "Please enter your password";
}
if(empty($_POST['password2'])) {
$pass2_error = "Please enter to confirm your password";
}
if( $_POST['password2'] != $_POST['password']){
$pass2_error = "The confirm password are incorrect!";
}
else{
header("location:registered.php");
}
}
?>
and here is the form code:
<main>
<div class="register-header d-flex flex-column align-items-center py-5">
<h1 class="font-rale text-dark gray-bg">
Sign up
</h1>
</div>
<form method="post" class="d-flex flex-column align-items-center py-5">
<div class="my-2">
<input type="text" class="name-input mx-1 p-2 border rounded" name="first-name"
placeholder="First name">
<input type="text" class="name-input mx-1 p-2 border rounded" name="last-name" placeholder="Last name">
</div>
<p class="text-center py-2 error"><?php echo $name_error;?></p>
<div class="my-2 p-1">
<input type="email" class="p-2 border rounded" name="email" placeholder="Your email">
</div>
<p class="text-center py-2 error"><?php echo $email_error;?></p>
<div class="my-2 p-1">
<input type="password" class="p-2 border rounded" name="password" placeholder="Your password">
</div>
<p class="text-center py-2 error"><?php echo $pass_error;?></p>
<div class="my-2 p-1">
<input type="password2" class="p-2 border rounded" placeholder="Confirm password">
</div>
<p class="text-center py-2 error"><?php echo $pass2_error;?></p>
<div class="my-2 p-1">
<input type="text" class="p-2 border rounded" name="contact" placeholder="Phone number (Optional)">
</div>
<button type="submit" name="register" class="my-3 px-3 py-2 text-light rounded border-0 form-button">Register</button>
<p>One of us? Sign in here.</p>
</form>
</main>
I have set all the errors to display under the div of each input.
and when I try to leave all input to be empty to test the validation. it doesn't work at all and I just head to the registered.php. Why the validation isn't displayed? Please help..
You must add some flag like:
if(isset($_POST['register'])) {
$flag_names = $flag_email = $flag_password = $flag_password2 = $flag_passwordmatch = true;
if(empty($_POST["first-name"] || $_POST["last-name"])) {
$name_error = "Please enter your name.";
$flag_names = false;
}
if(empty($_POST['email'])) {
$email_error = "Please enter the email";
$flag_email = false;
}
if(empty($_POST['password'])) {
$pass_error = "Please enter your password";
$flag_password = false;
}
if(empty($_POST['password2'])) {
$pass2_error = "Please enter to confirm your password";
$flag_password2 = false;
}
if( $_POST['password2'] !== $_POST['password']){
$pass2_error = "The confirm password are incorrect!";
$flag_passwordmatch = false;
}
if($flag_names && $flag_email && $flag_password && $flag_password2 && $flag_passwordmatch){
//Well I suppose if everything its ok then redirects to this page.
header("location:registered.php");
}
}
I'm just wondering if anyone knows how to make the errors shown on this screenshot: https://imgur.com/a/eaTVR9g go underneath their dedicated input boxes like shown on this image: https://imgur.com/a/Sb1AfUj If anyone is kind enough to do it for me I would greatly appreciate it. Thank you!
Here is my code:
<?php
$title = "Register";
include ($_SERVER['DOCUMENT_ROOT'] . '/private/header.php');
if ($AUTH) {
header ('Location: /');
die();
}
if (isset($_POST['go'])) {
$username = $_POST['username'];
$email = strtolower($_POST['email']);
$password = $_POST['password'];
$passwordConfirm = $_POST['confirmPassword'];
$protectedPassword = password_hash($password, PASSWORD_ARGON2I);
// Validation Checks
$errors = array();
$Emailstmt = $db->prepare("SELECT * FROM `Users` WHERE `Email` = :email;");
$Emailstmt->bindParam(':email', $email, PDO::PARAM_STR);
$Emailstmt->execute();
if ($Emailstmt->rowCount() > 0) {
$error[] = 'The email you tried to use is already being used on an different account, please use another one.';
}
$Userstmt = $db->prepare("SELECT * FROM `Users` WHERE `Username` = :username;");
$Userstmt->bindParam(':username', $username, PDO::PARAM_STR);
$Userstmt->execute();
$checkIP = $db->prepare("SELECT count(*) FROM `Users` WHERE `LastIP` = :regIP");
$checkIP->bindParam(":regIP", $UserIP, PDO::PARAM_STR);
$checkIP->execute();
$checkIpAdress = $checkIP->fetchColumn();
if (empty($checkIpAdress)) {
$checkIpAdress = 0;
}
if ($checkIpAdress) {
if ($checkIpAdress > 3) {
array_push($errors, 'It looks like you have registered too many accounts under this IP address.');
}
}
if (strlen($username) < 3) {
array_push($errors, 'Your username must be at least 3 characters in total.');
}
if (strlen($password) < 5) {
array_push($errors, 'Your password must be at least 5 characters in total.');
}
if ($Userstmt->rowCount() > 0) {
array_push($errors, 'The username you tried to use is already being used, Maybe try to pick another one.');
}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
//echo("$email is a valid email address");
} else {
array_push($errors, 'The email you specified(' . htmlspecialchars($email, ENT_QUOTES, "UTF-8") . ') is invaild.');
}
if (!preg_match("/^[a-zA-Z0-9][\w\.]+[a-zA-Z0-9]$/", $username)) {
array_push($errors, 'The username you specified(' . htmlspecialchars($username, ENT_QUOTES, "UTF-8") . ') contains special symbols or is invaild.');
}
if (strtolower($username) == strtolower($password)) {
array_push($errors, 'Your password can not be the same as your username.');
}
if ($password !== $passwordConfirm) {
array_push($errors, 'It looks like your passwords do not match.');
}
// Begin form submission
if (empty($errors)) {
$insert = $db->prepare("INSERT INTO `Users` (`Username`,`Email`,`Password`,`LastIP`,`TimeRegister`,`AvatarURL`) VALUES (:Username,:Email,:Password,:LastIP,:TimeRegister,:AvatarURL)");
$insert->bindParam(":Username", $username, PDO::PARAM_STR);
$insert->bindParam(":Email", $email, PDO::PARAM_STR);
$insert->bindParam(":Password", $protectedPassword, PDO::PARAM_STR);
$insert->bindParam(":LastIP", $UserIP, PDO::PARAM_STR);
$insert->bindParam(":TimeRegister", $now, PDO::PARAM_INT);
$insert->bindValue(":AvatarURL", '8ca17bec-0320-4293-90e5-dfc5b8690156', PDO::PARAM_STR);
$insert->execute();
?>
<div class="space">
<section class="hero is-success">
<div class="hero-body modal-button" data-target="modal" aria-haspopup="true"
style="padding: 1rem 1rem !important;">
<center>You have successfully registered! Please wait while we redirect you.</center>
</div>
</section><br>
</div>
<meta http-equiv='refresh' content='5;url=/auth/login' />
<?php
} else {
}
}
if ($SiteSettings->Registration == 0) {
echo '<section class="section">
<div class="container">
<div class="columns is-centered">
<div class="column is-7">
<div class="box">
<p>We\'re sorry, but account creation is currently disabled right now. Please try again later.</p>
</div>
</div>
</div>
</section>
';
include($_SERVER['DOCUMENT_ROOT'] . "/private/footer.php");
die;
}
?>
<section class="section">
<div class="container">
<div class="columns is-centered">
<div class="column is-7">
<div class="box">
<div class="title is-size-4">Register</div>
<form action="#" method="POST">
<input type="hidden" name="token" value="<?php echo $_SESSION["csrf_token"]; ?>" />
<div class="field">
<label class="label">Username</label>
<div class="control has-icons-left">
<input class="input" name="username" type="text" id="username" maxlength="15"
autocomplete="off" placeholder="Enter a username">
<span class="icon is-small is-left"><i class="fas fa-user"></i></span>
<p id="username_message"></p>
</div>
</div>
<div class="field">
<label class="label">E-Mail address</label>
<div class="control has-icons-left">
<input class="input" name="email" type="email" id="email" maxlength="128"
autocomplete="off" placeholder="Enter your e-mail address.">
<span class="icon is-small is-left"><i class="fas fa-envelope"></i></span>
<p id="email_message"></p>
</div>
</div>
<div class="field">
<label class="label">Password</label>
<div class="control has-icons-left">
<input class="input" name="password" type="password" id="password" maxlength="45"
autocomplete="off" placeholder="Enter your password.">
<span class="icon is-small is-left"><i class="fas fa-lock"></i></span>
<p id="password_message"></p>
</div>
</div>
<div class="field">
<label class="label">Confirm Password</label>
<div class="control has-icons-left">
<input class="input" name="confirmPassword" type="password" id="confirmPassword"
maxlength="45" autocomplete="off" placeholder="Confirm your password">
<span class="icon is-small is-left"><i class="fas fa-lock"></i></span>
<p id="confirmPassword_message"></p>
</div>
</div>
<div class="push-5"></div>
<button class="button is-success is-fullwidth" type="submit" name="go"><b>Register</b></button>
</form>
<?php
if (!empty($errors)) {
?>
<?php
foreach ($errors as $error) {
echo '<p class="help has-text-danger">' . $error . '</p>';
}
} ?>
</div>
<p class="has-text-centered">Already a member? Login</p>
</div>
</div>
</div>
</section>
<?php include ($_SERVER['DOCUMENT_ROOT'] . '/private/footer.php'); ?>
You can organize the array keys to reflect the fields they relate to, IE:
if (strlen($username) < 3) {
$errors['username'][] = 'Your username must be at least 3 characters in total.';
}
and then on the display side you can use said keys to identify what errors belong to what field, IE:
<div class="field">
<label class="label">Username</label>
<div class="control has-icons-left">
<input class="input" name="username" type="text" id="username" maxlength="15" autocomplete="off" placeholder="Enter a username">
<span class="icon is-small is-left"><i class="fas fa-user"></i></span>
<p id="username_message">
<?php if (isset($errors['username'])): ?>
<?php foreach($errors['username'] as $error): ?>
<?= $error ?> <br/>
<?php endforeach; ?>
<?php endif; ?>
</p>
</div>
I'm trying to enter data into a mysql database using php / html form but it isn't working and I don't know why. The record is not inserted and the page just refresh
I apologize for some of it being written in Danish
I have 2 files 1 with html and php and 1 with only php
My database: Database image
This is the html form and php:
<div class="row">
<div class="col-sm-12">
<?php
if (isset($_POST['Submit'])) {
// echo "<pre>", print_r($_POST), "</pre>";
$apply_name = mysqli_real_escape_string($db, $_POST ['apply_name']);
$apply_age = mysqli_real_escape_string($db, $_POST ['apply_age']);
$apply_ingame_name = mysqli_real_escape_string($db, $_POST ['apply_ingame_name']);
$apply_email = mysqli_real_escape_string($db, $_POST ['apply_email']);
$apply_steamID = mysqli_real_escape_string($db, $_POST ['apply_steamID']);
$apply_text = mysqli_real_escape_string($db, $_POST ['apply_text']);
$errors = []; // Array
if ($apply_name == "") {
$errors['apply_name'] = "<div class='alert alert-danger'>
<strong>Du har ikke angivet noget navn!</strong>
</div>";
} elseif (strlen($apply_name) < 2) {
$errors['apply_name'] = "<div class='alert alert-info'>
<strong>Dit navn skal minimum være 2 karatere</strong>
</div>";
}
if ($apply_age == "") {
$errors['create_apply_age'] = "<div class='alert alert-danger'>
<strong>Du har ikke angivet din alder!</strong>
</div>";
}
if ($apply_ingame_name == "") {
$errors['create_apply_ingame_name'] = "<div class='alert alert-danger'>
<strong>Du har ikke angivet noget In-Game navn!</strong>
</div>";
} elseif (strlen($apply_ingame_name) < 2) {
$errors['create_apply_ingame_name'] = "<div class='alert alert-info'>
<strong>Dit In-Game navn skal minimum være 2 karatere</strong>
</div>";
}
if ($apply_email == "") {
$errors['create_apply_email'] = "<div class='alert alert-danger'>
<strong>Email skal udfyldes!</strong>
</div>";
} elseif (!filter_var($apply_email, FILTER_VALIDATE_EMAIL)) {
$errors['create_apply_email'] = "<div class='alert alert-info'>
<strong>Email er ugyldig</strong>
</div>";
}
if ($apply_steamID == "") {
$errors['create_apply_steamID'] = "<div class='alert alert-danger'>
<strong>Du har ikke angivet noget SteamID!</strong>
</div>";
} elseif (strlen($apply_steamID) < 18) {
$errors['create_apply_steamID'] = "<div class='alert alert-info'>
<strong>Dit SteamID ser sådan her ud STEAM_0:0:XXXXXXXX</strong>
</div>";
}
if ($apply_text == "") {
$errors['create_apply_text'] = "<div class='alert alert-danger'>
<strong>Du har ikke skrevet noget om dig selv!</strong>
</div>";
}
if (empty($errors)) {
// Send ansøning
$created = create_apply($apply_name, $apply_age, $apply_ingame_name, $apply_email, $apply_steamID, $apply_text);
if ($created) {
echo "
<div class='alert alert-info'>
<strong>Din ansøning er sendt.</strong>
</div>
";
} else {
// Ansøning kunne ikke sendes
$create_error = "Ansøningen kunne ikke sendes, SteamID eksistere i forvejen";
}
} else {
$create_error = "Der opstod en fejl, Prøv igen";
}
}
?>
<section>
<hr>
<form class="form-horizontal" enctype="multipart/form-data" id="signup" method="post" name="signup" action="?p=askforsignup">
<?php
if (isset($errors['apply_name'])) {
echo $errors['apply_name'];
}
?>
<div class="form-group">
<label class="control-label col-sm-3">Navn <span class="text-danger">*</span></label>
<div class="col-md-8 col-sm-9">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user"></i></span><input class="form-control" id="mem_name" name="apply_name" placeholder="Navn" type="text" value="" >
</div>
</div>
</div>
<?php
if (isset($errors['create_apply_age'])) {
echo $errors['create_apply_age'];
}
?>
<div class="form-group">
<label class="control-label col-sm-3">Alder <span class="text-danger">*</span></label>
<div class="col-md-8 col-sm-9">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span><input class="form-control" id="age" name="apply_age" placeholder="Alder" type="date" value="" >
</div>
</div>
</div>
<?php
if (isset($errors['create_apply_ingame_name'])) {
echo $errors['create_apply_ingame_name'];
}
?>
<div class="form-group">
<label class="control-label col-sm-3">In-Game Name <span class="text-danger">*</span></label>
<div class="col-md-8 col-sm-9">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user"></i></span><input class="form-control" id="ingame_game" name="apply_ingame_name" placeholder="In-Game Name" type="text" value="" >
</div>
</div>
</div>
<?php
if (isset($errors['create_apply_email'])) {
echo $errors['create_apply_email'];
}
?>
<div class="form-group">
<label class="control-label col-sm-3">Email <span class="text-danger">*</span></label>
<div class="col-md-8 col-sm-9">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span><input class="form-control" id="emailid" name="apply_email" placeholder="Email" type="email" value="" >
</div><small>Your Email is being used for ensuring the security of your account, authorization and access recovery.</small>
</div>
</div>
<?php
if (isset($errors['create_apply_steamID'])) {
echo $errors['create_apply_steamID'];
}
?>
<div class="form-group">
<label class="control-label col-sm-3">Steam ID <span class="text-danger">*</span></label>
<div class="col-md-5 col-sm-8">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-steam"></i></span><input class="form-control" id="contactnum" name="apply_steamID" placeholder="Steam ID" type="text" value="" >
</div>
</div>
</div>
<?php
if (isset($errors['create_apply_text'])) {
echo $errors['create_apply_text'];
}
?>
<div class="form-group">
<label class="control-label col-sm-3">Beskriv dig selv <span class="text-danger">*</span></label>
<div class="col-md-8 col-sm-9">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-id-card"></i></span>
<textarea class="form-control" rows="5" id="message" name="apply_text" placeholder="Beskriv dig selv." ></textarea>
</div><br>
<div class="col-xs-offset-8 col-xs-10 pull-right">
<input class="btn btn-primary" name="Submit" type="submit" value="Sign Up">
</div>
</div>
</div>
</form>
</section>
</div><!--/.col-sm-8-->
</div>
And this is the php code:
function create_apply($apply_name, $apply_age, $apply_ingame_name, $apply_email, $apply_steamID, $apply_text) {
global $db;
$steamID_exists = steamID_exists($apply_steamID);
if ($steamID_exists == false) {
$apply_name = mysqli_real_escape_string($db, $apply_name);
$apply_age = mysqli_real_escape_string($db, $apply_age);
$apply_ingame_name = mysqli_real_escape_string($db, $apply_ingame_name);
$apply_email = mysqli_real_escape_string($db, $apply_email);
$apply_steamID = mysqli_real_escape_string($db, $apply_steamID);
$apply_text = mysqli_real_escape_string($db, $apply_text);
$query = "INSERT INTO member_applys
(apply_name, apply_age, apply_ingame_name, apply_email, apply_steamID, apply_text, apply_date)
VALUES
('$apply_name', '$apply_age', '$apply_ingame_name', '$apply_email', '$apply_steamID', '$apply_text', NOW())";
$result = $db->query($query);
return true;
} else {
// Brugeren eksistere opret = falsk
return false;
}
}
Solved
the problem was google autocomplete was on not off
Di you be sure that your script call well the form?
I see:
....action="?p=askforsignup">
try:
....action="your_script.php">
In the following code in crudindex.php if I enter password with length less than 6 characters error message is not showing using the span command.Required pattern is working. But messages using span command is not displaying ex : if i enter length less than 6 in password no error message displays
What is wrong in this code?
<?php
$con = mysqli_connect("127.0.0.1", "kkits996_ganesh", "", "kkits996_testmysql") or die("Error " . mysqli_error($con));
$error=false;
if (isset($_POST) && (!empty($_POST))){
$uname=mysqli_real_escape_string($con,$_POST["uname"]);
$pwd=mysqli_real_escape_string($con,$_POST["pwd"]);
$cpwd=mysqli_real_escape_string($con,$_POST["cpwd"]);
$password_error="";
$cpassword_error="";
if(strlen($pwd) < 6) {
$error = true;
$password_error = "Password must be minimum of 6 characters";
}
if($pwd != $cpwd) {
$error = true;
$cpassword_error = "Password and Confirm Password doesn't match";
}
if (isset($_POST['register'])) {
# Register-button was clicked
$createsql1="INSERT INTO cruduser(id,username,password) VALUES
('','$uname','$pwd')";
if (mysqli_query($con,$createsql1)) {
echo "Insert Successful in Table cruduser";
mysqli_close($con);
//Redirect because we need to consider the post request from crudadd.php
header( 'Location: crudaddusr.php' ) ;
//include ("crudadd.php");
}
else
{
die(mysqli_error($con));
}
}
if (isset($_POST['login'])) {
# Login-button was clicked
session_start();
$SESSION['suname']=$uname;
$SESSION['spwd']=$pwd;
if ($uname=='admin' && $pwd=='admin') {
include('crudview.php');
}
else
{
header( "Location: crudeditusr.php?suname=$uname&spwd=$pwd");
}
}
mysqli_close($con);
}
?>
<!--DocType HTML -->
<! bootstrap link is downloaded from bootstrapcdn.com for css and js -->
<! col-mod-6 col-mod-offset are bootstrap related-->
<HTML>
<head>
<title>"Add records in CRUD Table"</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<form method="post" class="form-horizontal col-mod-6 col-mod-offset-3">
<h2>Create The table CRUD</h2>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Username : </label>
<div class="col-sm-10">
<input type="text" name="uname" required pattern="^[A-Za-z0-9]+" class="form-control" id="input1" placeholder="Username"/>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Password: </label>
<div class="col-sm-10">
<input type="password" name="pwd" required pattern="^[A-Za-z0-9]+" class="form-control" id="input1" placeholder="Password"/>
<span class="error"><?php if (isset($password_error)) echo $password_error;?></span>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Confirm Password : </label>
<div class="col-sm-10">
<input type="password" name="cpwd" required pattern="^[A-Za-z0-9]+" class="form-control" id="input1" placeholder="Confirm Password"/>
<span class="text-danger"><?php if (isset($cpassword_error)) echo $cpassword_error; ?></span>
</div>
</div>
<div class="row">
<div class="col-mod-6 col-mod-offset-3">
<button id="submit1" name="register" class="btn btn-primary pull-right">Register</button>
<button id="submit2" name="login" class="btn btn-secondary pull-right">Login</button>
</div>
</div>
</form>
</body>
</html>
This is a working example to display your errors and prevent some security problems. I have removed the required pattern from your html. You didn't properly set errors. You can handle errors with php and display them. Plus you didn't use action="path/to/handleform.php".
And your redirect should be in login: header( "Location: crudeditusr.php?suname=".$uname."&spwd=".$pwd);
There are 3 security problems here:
SQL injection. SOLUTION=> prepared statement
Password saved as plain text. SOLUTION=> password_hash()
Cross-Site Request Forgery (CSRF). SOLUTION=> input hidden with a token
<?php
$con = mysqli_connect("127.0.0.1", "kkits996_ganesh", "", "kkits996_testmysql") or die("Error " . mysqli_error($con));
// Declare array for errors
$error=array();
//-----------------------------------------------------//
//---------------------CSRF PROTECT--------------------//
//-----------------------------------------------------//
//generate a token/
function generateToken( $formName )
{
//secret_key change it
$secretKey ='?#GEskki58668445744!Erpoejsj48';
if ( !session_id() )
{
session_start();
}
$sessionId = session_id();
return hash('sha512', $formName.$sessionId.$secretKey );
}
//check if the token is valid
function checkToken( $token, $formName)
{
return $token === generateToken( $formName );
}
//Separate REGISTER AND LOGIN TO NOT BE CONFUSED//
//-----------------------------------------------------//
//---------------------REGISTRATION--------------------//
//-----------------------------------------------------//
if ( isset($_POST['register']) && checkToken( $_POST['csrf_token'], 'userFromRegistration' ) )
{
//if the username required
if(!preg_match('/^[A-Za-z0-9]+$/',$_POST['uname']))
{
$error['username'] = "Username must have alphanumeric characters ";
}
//if password has less than 6 characters
if(strlen($_POST['pwd']) < 6)
{
$error['password'] = "Password must be minimum of 6 characters";
}
//if password does not match
if($_POST['pwd'] !== $_POST['cpwd'] OR empty($_POST['cpwd']) )
{
$error['passwordmatch'] = "Password and Confirm Password doesn't match";
}
//if empty error array
if( !array_filter($error) )
{
//trim data
$username = trim( $_POST['uname'] );
// Hash you password, never save PASSWORD AS PLAIN TEXT!!!!!!!
// MYSQL! : Allow your storage to expand past 60 characters (VARCHAR 255 would be good)
$password = password_hash( $_POST['pwd'], PASSWORD_DEFAULT);
//if the id is autoincremented leave id
//----------USE PREPARED STATEMENT FOR SQL INJECTION---//
$query = 'INSERT INTO cruduser (username, password) VALUES (?,?)';
$stmt = $con->prepare($query);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->close();
$con->close();
//Redirect because we need to consider the post request from crudadd.php
header( 'Location: crudaddusr.php' ) ;
}
}
//-----------------------------------------------------//
//------------------------LOGIN------------------------//
//-----------------------------------------------------//
if (isset($_POST['login']))
{
//what ever you want
//Use password_verify() and session_regenerate_id()
//to compare passwords and to generate a session id to prevent session fixation.
session_start();
$uname = $_POST['uname'];
$pwd = $_POST['pwd'];
//if you don't need it delete it
$SESSION['suname']=$unmane;
$SESSION['spwd']=$pwd;
if ($uname=='admin' && $pwd=='admin')
{
include('crudview.php');
}
else
{
header( "Location: crudeditusr.php?suname=".$uname."&spwd=".$pwd);
}
}
?>
<!--HTMl PART-->
<!DOCTYPE html>
<html>
<head>
<title>"Add records in CRUD Table"</title>
<!-- bootstrap link is downloaded from bootstrapcdn.com for css and js -->
<!-- col-mod-6 col-mod-offset are bootstrap related-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<form method="post" action="" class="form-horizontal col-mod-6 col-mod-offset-3">
<input type="hidden" name="csrf_token" value="<?php echo generateToken('userFromRegistration'); ?>" required/>
<h2>Create The table CRUD</h2>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Username : </label>
<div class="col-sm-10 <?php if( !empty( $error['username'] ) ){ echo 'has-error';} ?> ">
<input type="text" name="uname" class="form-control" id="input1" placeholder="Username"/>
<span class="help-block"><?php if (!empty($error['username'])) echo $error['username'];?></span>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Password: </label>
<div class="col-sm-10 <?php if( !empty( $error['password'] ) ){ echo 'has-error';} ?>">
<input type="password" name="pwd" class="form-control" id="input1" placeholder="Password"/>
<span class="help-block"><?php if (!empty($error['password'])) echo $error['password'];?></span>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Confirm Password : </label>
<div class="col-sm-10 <?php if( !empty( $error['passwordmatch'] ) ){ echo 'has-error';} ?>">
<input type="password" name="cpwd" class="form-control" id="input1" placeholder="Confirm Password"/>
<span class="help-block"><?php if (!empty($error['passwordmatch'])) echo $error['passwordmatch'];?></span>
</div>
</div>
<div class="row">
<div class="col-mod-6 col-mod-offset-3">
<button id="submit1" name="register" class="btn btn-primary pull-right">Register</button>
<button id="submit2" name="login" class="btn btn-secondary pull-right">Login</button>
</div>
</div>
</form>
</body>
Change this line from this,
$pwd=mysqli_real_escape_string($con,$_POST["pwd"]);
to this,
$pwd=mysqli_real_escape_string($_POST["pwd"]);
You don't need to add $con to assign your password to another variable but it's better use the direct $_POST variable no need to assign it to another.
if(strlen($_POST["pwd"]) < 6) {
$error = true;
$password_error = "Password must be minimum of 6 characters";
}
Basically if the user comes to the page they get a form where they type in their username. That then checks against the db and then adds a generated key to their row in the db and emails the key link to them. The link brings them back to the same page but with a different form asking to update their password.
This is where my problem lies. The script first checks if that key exists. Even though it does exist I keep getting the uh oh key does not exist error. I've read through it a few times, taken breaks and still can't get it. Hopefully someone here can catch the issue!
Snippet of the problem:
<?php
if ($_GET['do'] == "password") {
$forgetKeyEmail = mysql_real_escape_string($_GET['key']);
if ($forgetKeyEmail !== "") {
$keyQuery = mysql_query("SELECT * FROM users WHERE forgetKey = '$forgetKeyEmail' LIMIT 1");
$keyCheck - mysql_num_rows($keyQuery);
if ($keyCheck == 1) {
?>
form goes here to update password
<?php
if ($_GET['do'] == "update") {
$hasher = new PasswordHash(10, false);
$resetPasswdord = $hasher->HashPassword(mysql_real_escape_string($_POST['inputPassword']));
$resetPassword = $_POST['inputPassword'];
if ($_POST['inputPassword'] !== "") {
mysql_query("UPDATE users SET password = '$resetPassword' WHERE forgetKey = '$forgetKeyEmail'");
echo "g";
?>
success message
<?php
}
else {
?>
empty field message
<?php
}
}
}
else{
?>
incorrect key message (what I keep getting)
<?php
}
}
}
Full code:
<?php
if ($_GET['do'] == "password") {
$forgetKeyEmail = mysql_real_escape_string($_GET['key']);
if ($forgetKeyEmail !== "") {
$keyQuery = mysql_query("SELECT * FROM users WHERE forgetKey = '$forgetKeyEmail' LIMIT 1");
$keyCheck - mysql_num_rows($keyQuery);
if ($keyCheck == 1) {
?>
<form method="POST"class="form-horizontal" action="?do=update&key=<?php echo $forgetKeyEmail; ?>" >
<div class="control-group">
<label class="control-label" for="inputPassword">New Password</label>
<div class="controls">
<input type="text" id="inputPassword" name="inputPassword" placeholder="Password">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">Reset!</button>
</div>
</div>
</form>
<?php
if ($_GET['do'] == "update") {
$hasher = new PasswordHash(10, false);
$resetPasswdord = $hasher->HashPassword(mysql_real_escape_string($_POST['inputPassword']));
$resetPassword = $_POST['inputPassword'];
if ($_POST['inputPassword'] !== "") {
mysql_query("UPDATE users SET password = '$resetPassword' WHERE forgetKey = '$forgetKeyEmail'");
echo "g";
?>
<div class="alert alert-success" style="margin:0;">
<strong>Woooo!</strong> Your password has been changed, you can now login.
</div>
<?php
}
else {
?>
<div class="alert alert-error" style="margin:0;">
<strong>Woops!</strong> You need to fill out a password!
</div>
<?php
}
}
}
else{
?>
<div class="alert alert-error" style="margin:0;">
<strong>Uh oh!</strong> That key is incorrect.
</div>
<?php
}
}
}
elseif ($_GET['do'] == "reset") {
$resetUsername = mysql_real_escape_string($_POST['inputUser']);
if ($resetUsername !== "") {
$checkQuery = mysql_query("SELECT * FROM users WHERE username = '$resetUsername' LIMIT 1");
$checkExist = mysql_num_rows($checkQuery);
$userData = mysql_fetch_array($checkQuery);
$mailEmail = $userData['email'];
if ($checkExist == 1) {
$forgetKey = genRandomString() . genRandomString();
mysql_query("UPDATE users SET forgetKey = '$forgetKey' WHERE username = '$resetUsername'");
$message = "Hey there, ".$resetUsername." - We've received a request to reset your password. <br /><br /> Please click the following link to do so: <a href=\"http://localhost/vanilla/forgot.php?do=reset&key=".$forgetKey."\"";
echo $forgetKey;
mail($mailEmail, 'realvanil.la Password Reset', $message);
?>
<div class="alert alert-info" style="margin:0;">
An email has been sent to <strong><?php echo $userData['email']; ?></strong> with your reset information!
</div>
<?php
}
else {
?>
<div class="alert alert-error">
<strong>Uh oh!</strong> We can't seem to find an account with that username. Remember, it's your Minecraft username!
</div>
<form method="POST"class="form-horizontal" action="?do=reset" >
<div class="control-group">
<label class="control-label" for="inputUser">Username</label>
<div class="controls">
<input type="text" id="inputUser" name="inputUser" placeholder="Username">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">Send Email!</button>
</div>
</div>
</form>
<?php
}
}
else {
?>
<div class="alert alert-error">
<strong>Uh oh!</strong> You need to tell us your username ;)
</div>
<form method="POST"class="form-horizontal" action="?do=reset" >
<div class="control-group">
<label class="control-label" for="inputUser">Username</label>
<div class="controls">
<input type="text" id="inputUser" name="inputUser" placeholder="Username">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">Send Email!</button>
</div>
</div>
</form>
<?php
}
}
else {
?>
<form method="POST"class="form-horizontal" action="?do=reset" >
<div class="control-group">
<label class="control-label" for="inputUser">Username</label>
<div class="controls">
<input type="text" id="inputUser" name="inputUser" placeholder="Username">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">Send Email!</button>
</div>
</div>
</form>
<?php
}
?>
you may want to edit you script so it does not have any syntax errors.
$keyCheck - mysql_num_rows($keyQuery);
change to
$keyCheck = mysql_num_rows($keyQuery);