password minimal length doesn't work - php

I want my password to be at least 6 characters long and if it is less than 6 characters long it has to say an error but it does not say anything.
<?php
if (strlen($_POST['userPassword']) < 6 ) {
$error[]= "wachtwoord moet minimaal 6 karakters bevatten <br />";
} else {
$cryptpass = md5($password);
$query = $dbcon->prepare("INSERT INTO users (userName,userPassword,userMail) VALUES (:userName,:userPassword, :userMail)");
$query->bindParam(":userName", $_POST['userName']);
$query->bindvalue(":userPassword", $cryptpass);
$query->bindParam(":userMail", $_POST['userMail']);
$query->execute();
echo "gebruiker aangemaakt";
}
foreach ($error as $errors) {
echo $errors;
}
?>
this is my form:
<form action="registratie.php" method="post">
Username <br />
<input type="text" id="user_input" name="userName" placeholder="userame" /><br />
Password<br />
<input type="password" id="pass_input" name="userPassword" placeholder="password" /><br />
Password<br />
<input type="password" id="v_pass_input" name="userPassAgain" placeholder="password" /><br />
Email<br />
<input type="email" id="email" name="userMail" placeholder="email"><br />
<input type="submit" id="register" name="register" value="Register" disabled="disabled" />
</form>

Taken from comments:
"plus, is the form and PHP/PDO in the same file? how is this accessed, on a hosted site? local? if local, http://localhost/file.xxx or file:///file.xxx??
and
"#fred-ii- it is local. it is accessed like : file:///file.xxx – Furkan yavuz"
and
"there is the problem ^ #Furkanyavuz and why is this disabled="disabled" /> for submit disabled?"
There's the problem. You have to run this off a webserver and not as file:///file.xxx directly in your web browser.
The browser itself won't parse PHP directives.
But as http://localhost/file.xxx or http://example.com/file.xxx.
If you don't have a webserver/PHP installed, you will have to install one or run it off a hosted website.
Sidenote: If you're running this off the same file, you will first need to check if the inputs are empty or not.
Reference: http://php.net/manual/en/function.empty.php
Also, since you're using PDO, why are you using MD5 to store passwords with? It is no longer safe to do so now.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP
Important sidenote about column length:
If and when you do decide to use password_hash() or crypt, it is important to note that if your present password column's length is anything lower than 60, it will need to be changed to that (or higher). The manual suggests a length of 255.
You will need to ALTER your column's length and start over with a new hash in order for it to take effect. Otherwise, MySQL will fail silently.
Footnotes:
Comments from Ali Zia:
You can fix that by using if (isset($_POST['userPassword']) && strlen($_POST['userPassword']) < 6 ) #Furkanyavuz – Ali Zia 2 mins ago
Also if (!empty($error)){ before foreach – Ali Zia 1 min ago
Sidenote: Using !empty() over isset() is better as it checks if it's both set and empty.
if (!empty($_POST['userPassword']) && strlen($_POST['userPassword']) < 6 )
Regarding PDO/query/connection.
The connection is unknown, whether it is in fact PDO.
Note that different MySQL APIs do not intermix. So, if you're using mysqli_ or mysql_ to connect with, that won't work with your PDO query.

Related

php - Can't get the right if else condition in regards of variables connecting to the database

Really can't finish my project because of this condition. My project is a Login Page.
It always continues to the first if condition, but it is for else condition. I just only started studying this php now, although it is being taught to us last week.
login.php
<?php
session_start();
include 'register/dbconnect.php';
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
$sql = "SELECT * FROM user WHERE uid='$uid' AND pwd='$pwd'";
$result = mysqli_query($connect, $sql);
if (!$row = mysqli_fetch_assoc($result)) {
header("Location: index.php");
} else {
header("Location: login/home/home.php");
}
?>
index.php (in the login form part)
<form action="login.php" method="POST">
<input type="text" name="uid" class="loginField" placeholder="Enter your username" required><br />
<input type="password" name="pwd" id="passss" class="loginField" placeholder="Enter your password" required>
<img src="withAcc/img/blindeye.png" onMouseOver="showPass()" onMouseOut="hidePass()" id="eye1" class="eyes"><br /><br />
<p><input type="checkbox" id="keepSigned" value=""> <label for="keepSigned">Stay signed in</label>
Forgot password?</p>
<input type="Submit" value="Login" id="logInBut" ><br />
<p>Do you have an account? Register</p>
</form>
Edited login.php
if (!$row = $result->fetch_assoc()) {
header("Location: index.php");
} else {
header("Location: login/home/home.php");
}
I edited it like this, but it neither works. It always going to index.php, although the username and password is stored in the database.
This is a pretty strange condition:
if (!$row = mysqli_fetch_assoc($result)) {
And I can't help but wonder if some combination of operator precedence and query success/failure is going to silently produce unexpected results here. I imagine a more intuitive way of doing this would be to check the number of rows in the query result:
if (mysqli_num_rows($result) > 0) {
However, there are a couple other improvements you should make as well to round this out a bit better. First, as mentioned in comments on the question above, you should definitely make use of prepared statements to avoid SQL injection. This is important not only for security but also for general stability and debugging of your code. (Directly using input as code like you currently do makes you much more responsible for the syntax of that code, which often leads to errors.)
Additionally, after executing a query (and before examining the results of that query, so before your if statement) you should check if the query was successful. If it's not successful, your $result variable will be null. So check if $result is null and if it is, don't try to use it for logging in. Instead, examine the error from the database. Something as simple as:
echo mysqli_error($connect);
Also, and this is very important, you are currently storing user passwords in plain text. This is a very, very bad thing. User passwords should always be hashed so that they can't be retrieved in their original form. PHP has some built-in functionality to help with this.

Can't get my data Inserted into MySQL database, using PHP

I am working on a school project and can't get registration page done right. It just doesn't insert the data in table.
Here is a screenshot for database and table
I have added the HTML, and after going through all your answers I think I am using outdated videos and study material to learn (PHP, HTML, CSS, Website Security).
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Register</title>
</head>
<body>
<div class="form">
<h2>Registeration</h2>
<form action="" method="post">
Name<input type="text" name="name" placeholder="First & Last name" required><br><br>
Username<input type="text" name="username" placeholder="Username"required><br><br>
Password<input type="password" name="password" placeholder="Keep it Strong"required><br><br>
Confirm Password<input type="password" name="confirm-pass" placeholder="Re-Enter Password"required><br><br>
Email<input type="email" name="email" placeholder="Email"required><br><br>
Phone No.<input type="text" name="phone-no" placeholder="Phone No"required><br><br>
Gender<input type="text" name="gender" placeholder="Male or Female"required><br><br>
State<input type="text" name="state" placeholder="State"required><br><br>
<button type="submit" name="home">Home</button>
<button type="submit" name="sub">Submit</button>
<button type="submit" name="reset">Reset</button>
</form>
</div>
</body>
</html>
<?php
$con=mysqli_connect('localhost','root','123456789','eedb');
if ($con)
{
if (isset($_POST['sub']))
{
$n= $_POST['name'];
$un=$_POST['username'];
$p=$_POST['password'];
$cp=$_POST['confirm-pass'];
$e=$_POST['email'];
$pn=$_POST['phone-no'];
$g=$_POST['gender'];
$s=$_POST['state'];
mysqli_query($con,"SELECT * FROM `register`");
$insert= mysqli_query($con,"INSERT INTO `register`(`name`, `username`, `password`, `confirm-pass`, `email`, `phone-no`, `gender`, `state`) VALUES ('$n','$un','$p','$cp','$e','$pn','$g','$s')");
if ($insert)
{
echo "<center>Data Successfully Submitted</center>";
}
else
{
echo "<center>Data Not Submitted</center>";
}
}
}
else
{
echo "<center>Oh!no there is an error.<br><br>But don't worry we have an army of trained chimpanzies to deal with it.<br><br> <image src='images/chimps.jpg'><br><br>Come Back Soon</center>";
}
if (isset($_POST['home']))
{
header("location:index.php");
}
if (isset($_POST['reset']))
{
header("location:register.php");
}
?>
Since you didn't post your HTML form, I am posting the following answer, which is what your HTML form should (basically) look like, which btw only contains the one example element.
You will need to fill in the rest and follow the same convention.
<form method="post" action="handler.php">
First name:
<input type="text" name="name">
<br>
<input type="submit" name="sub" value="Submit">
</form>
Then escape your values, should there contain any characters that MySQL may complain about, such as apostrophes.
I.e.: Doug's Bar & Grill.
Then:
$n= mysqli_real_escape_string($con, $_POST['name']);
Something you should use or a prepared statement since your code is presently open to an SQL injection.
Ref: How can I prevent SQL injection in PHP?
And do the same for all your other POST arrays.
The name attribute is required for POST arrays when using pure PHP and a post method for the HTML form.
Sidenote: Your entire code is dependant on the following conditional statement
if (isset($_POST['sub'])){...}. So make sure that that form element bears the same name attribute for it.
Check for errors also.
Since this does not help you:
echo "<center>Data Not Submitted</center>";
References:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
It's unclear as to what you're trying to do with this line:
mysqli_query($con,"SELECT * FROM `register` ");
If the goal is to check if a row exists, then consult one of my answers on Stack:
check if row exists with mysql
Passwords
I also noticed that you may be storing passwords in plain text. This is not recommended.
Use one of the following:
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Important sidenote about column length:
If and when you do decide to use password_hash() or the compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/, it is important to note that if your present password column's length is anything lower than 60, it will need to be changed to that (or higher). The manual suggests a length of 255.
You will need to ALTER your column's length and start over with a new hash in order for it to take effect. Otherwise, MySQL will fail silently.
Other links of interest:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PBKDF2 For PHP
HTML stickler:
The <center> tag is deprecated and has been removed from Web standards.
For more information, visit the following:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/center
you can try this
$insert= mysqli_query($con,"INSERT INTO `register`(`name`, `username`, `password`, `confirm-pass`, `email`, `phone-no`, `gender`, `state`)VALUES ('$n','$un','$p','$cp','$e','$pn','$g','$s')");
you can try to use notepad++ or any other editor (e.g netbeans )that will make the open and closed brackets more obvious .

PHP Mysql Forum User Creation Script doesn't work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
My code doesn't work, nor it gives me any errors, so the code is right, but still doesn't work.
The code aims to look up for the entered data of a HTML form and, if the entered values are not stored on the database, creating them(the new user).
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('SECURE', true);
require_once('_connecting.php');
include "_head.php";
if(isset($_POST["send"]))
{
$username = $_POST["user_name"];
$mail=$_POST["user_email"];
$passwort = $_POST["user_password"];
$passwort2 = $_POST["user_password2"];
if(strlen($passwort)<6||$passwort!=$passwort2)
{
echo "Eingabefehler. Bitte alle Felder korekt ausfüllen. Zurück";
}
else
{
$check = ("SELECT Count(*) FROM user WHERE user_email ='$mail'");
$mysqli->query($check);
if ($check > 1) {
echo "Schon vorhanden";
exit();
} else {
$send="INSERT INTO user (user_name, user_email,user_password) VALUES ('$username','$passwort','$mail')";
$mysqli->query($send);
}
}}
?>
<h1>
Registriere dich jetzt, um alle Funktionen des Forums in vollem Umfang genießen zu können.
</h1>
<h1 id="yellowh1">
Du wirst es nicht bereuen - Es warten viele spannende Dinge auf dich.
</h1>
<form action="signup.php" method="post">
<br><br>
<input type="text" name="user_name" value="" required="required" placeholder="Nutzername" maxlength="255" />
<br>
<br>
<input type="email" name="user_email" value="<?php echo !empty($_POST['user_email']) ? $_POST['user_email'] : ''; ?>" required="required" placeholder="E-Mail-Adresse" maxlength="255" />
<br><br>
<input type="password" name="user_password" required="required" placeholder="Passwort" maxlength="50" />
<input type="password" name="user_password2" required="required" placeholder="Passwort erneut eingeben" maxlength="50" />
<br><br>
<input type="submit" value="Abschicken" name="send">
</form>
<?php include "_footer.php";?>
There are a few problems here.
$mail=$_POSST["user_email"];
Firstly, there is a typo in there and you must remove one of the S's. It's a superglobal.
Having error reporting would have signaled:
Notice: Undefined variable: _POSST in...
As I stated in comments, your query depends on it. WHERE user_email ='$mail' and you're not checking for errors anywhere.
VALUES ('$username','$passwort','$mail') that will also fail because of the typo in $_POSST.
Then you have value="<?php echo $user_email; ?>" for the name="user_email" input, which will also throw the following notice in the input field itself, as soon as you hit the submit button:
Notice: Undefined variable: user_email in...
Therefore, you need to use a ternary operator:
value="<?php echo !empty($_POST['user_email']) ? $_POST['user_email'] : ''; ?>"
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Footnotes:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
References:
http://php.net/manual/en/language.operators.comparison.php
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/language.variables.superglobals.php
http://php.net/manual/en/mysqli.error.php
Final notes:
Since the MySQL API to connect with is unknown (to me), make sure that you are in fact using mysqli_ to connect with, and not another one that is different. Different MySQL APIs do not intermix with each other.
Use the same API from connection to query.
https://php.net/mysqlinfo.api.choosing
As stated in comments and kudos to "Don't Panic":
$mysqli->query->execute seems kind of strange. – Don't Panic
This method of querying $mysqli->query->execute(...) is used for prepared statements. http://php.net/manual/en/mysqli.prepare.php
Those need to be modified as just $mysqli->query(...)
As per the manual http://php.net/manual/en/mysqli.query.php

PHP echo doesn't echo certain output

So I've been fooling around on a very simple design for a database that has a feature to allow an admin to log in and edit some of the products. This is the current layout of getting the username and password from the log in form:
$manager = $_POST["username"];
$password = $_POST["password"];
$manager = stripslashes($manager);
$password = stripslashes($password);
$manager = mysql_real_escape_string($manager);
$password = mysql_real_escape_string($password);
I've created log in scripts before but for some reason I'm having trouble with this log in actually working. So I was checking what some variables were being passed as in order to see where the problem was occurring when I got to these lines:
echo "manager = " . $manager . "<br />";
echo "password = " . $password . "<br />";
$sql = "SELECT * FROM admin WHERE username='$manager' AND password='$password'";
echo $sql;
The output was:
manager = scott
password = password123
SELECT * FROM admin WHERE username='scott' AND password=''
where the $password variable was removed from the output of the $sql string. Any suggestions on why it is leaving out the $password variable?
Here is the HTML form code:
<form id="form1" name="form1" method="post" action="admin_login.php">
Username:<br />
<input name="username" type="text" id="username" size="40" />
<br /><br />
Password:<br />
<input name="password" type="password" id="password" size="40" />
<br /><br /><br />
<input type="submit" name="button" id="button" value="Log In" />
</form>
To close this question:
SQL uses password() as a function and will not show a password for security reasons when using that word. Here's some documentation on it:
https://dev.mysql.com/doc/refman/5.0/en/set-password.html
https://dev.mysql.com/doc/refman/5.1/en/password-hashing.html
Therefore, use another name for the password variable.
Passwords
I also noticed that you are storing passwords in plain text. This is not recommended.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Other links:
PBKDF2 For PHP
Footnotes:
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
$sql = "SELECT * FROM admin WHERE username='" .$manager. "' And password='" .$password. "';
Try this

How could I limit the password to be a certain number of characters?

I need to limit the password characters to be 10 only as an example, not less not more..
There's only "maxlength" in HTML attributes, but there's no such "length" or "minlenght" to be used!
I have this code:
<input type="password" name="password" maxlength="9" pattern="\d+" value="<?php echo htmlentities($password); ?>" />
How could I limit the password to be a certain number of characters?
You could use JavaScript to do it. First attach the onblur event:
<input ... onblur="verifyMinLength(this, 10)"... />
and then in JavaScript:
function verifyMinLength(o, len) {
if (o.value.length < len) {
alert('The password must be 10 characters in length.');
o.focus();
}
}
of course this could be fancier. You could leverage a label that's placed next to the input control instead of the alert. You could also use CSS to change the border of the input control so the user gets some more feedback. But that's all up to you.
You can use HTML5. For me it's a good solution.
<form action="#" method="POST" id="form">
<input pattern=".{10}" title="10 characters" placeholder="10 characters" name="password" type="password" />
<input type="submit" value="Test" />
</form>
See in action: http://jsfiddle.net/a4B7z/.
Not supported in Internet Explorer 9 and earlier versions, or in Safari.
Why not use strlen?
if(strlen($password) < 10)
You need to validate the password after it is entered:
if (strlen($password) != 10)
{
echo 'password must be 10 characters';
}
Well I see you already have a lot of good answers here. Using a validation pattern like freejosh posted is the way I would do it. It seems to me to be the simplest and cleanest approach.
BUT.....
I have to agree with sammitch on this one. I would never limit a passwords length for the reasons he already stated. Having a minimum length can be a good thing since it forces the password to have a certain number of characters therefore (hopefully) increasing its security, but I would never give a limit for maximum length

Categories