PHP MD5 Create User Form - php

I have used a tutorial here: http://www.phpeasystep.com/phptu/26.html to create a login form for my website. I have set the uPassword field in my database to be md5 and all of the passwords in the database are encrypted with md5.
The login works perfectly, however I am slightly confused about creating a registration form.
The form requests for a user to input their desired password. I am slightly confused as to how I will then take the password that the user inputs, converting it to md5 and then inputting the md5 password into the uPassword field in the user table.
Below is the code that I have for the processresgistration.php file:
/* Database connection info*/
mysql_select_db("dbname", $con);
$encryptedpassword = md5($_POST['uPassword']);
md5($uPassword);
$sql="INSERT INTO users (uName, uPassword, uSurname, uFirstName)
VALUES
('$_POST[uName]','$encryptedpassword','$_POST[uSurname]','$_POST[uFirstName]'";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Account created. You can now login";
mysql_close($con)
?>
The code above is supposed to:
Create a variable named encryptedpassword
Use uPassword as encryptedpassword
Convert encrypted password to MD5
Input the MD5 password into the users table as uPassword
I'm sure that I've not used a correct variable somewhere, or I have done a simple error with my syntax; any comments/help is greatly appreciated!
Thanks,
Chris M

You code require some validation & escaping, more like this :
<?php
/* Database connection info */
mysql_select_db("dbname", $con);
if ($_REQUEST['METHOD'] == 'POST') {
$uName = filter_input(INPUT_POST, 'uName');
$uPassword = filter_input(INPUT_POST, 'uPassword');
$uSurname = filter_input(INPUT_POST, 'uSurname');
$uFirstName = filter_input(INPUT_POST, 'uFirstName');
// do some validation here ...
// if everything OK, then crypte the password
$hashedPassword = md5($uPassword);
// and store it
$sql = sprintf(
'INSERT INTO users (uName, hashedPassword, uSurname, uFirstName)
VALUES (%s, %s, %s, %s);',
mysql_real_escape_string($uName, $con),
mysql_real_escape_string($hashedPassword, $con),
mysql_real_escape_string($uSurname, $con),
mysql_real_escape_string($uFirstName, $con)
);
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
mysql_close($con);
echo "Account created. You can now login";
}
?>
Now for login
<?php
if ($_REQUEST['METHOD'] == 'POST') {
$uName = filter_input(INPUT_POST, 'uName');
$uPassword = filter_input(INPUT_POST, 'uPassword');
$hashedPassword = md5($uPassword);
$sql = sprintf(
'SELECT * FROM users WHERE uName = "%s" AND hashedPassword = "%s" LIMIT 1',
mysql_real_escape_string($uName, $con),
mysql_real_escape_string($hashedPassword, $con),
);
// etc etc ...
}
?>

/* Database connection info*
You didn't properly close your comment there. Add a / at the end of the line.
Oh, and MD5 is insecure. Use SHA1 instead. Or even better, use salted SHA1.
You also need to start escaping all user input you are putting in your database using mysql_real_escape_string() or Little Bobby Tables will have lots of fun with your database.

/* Database connection info*/
mysql_select_db("dbname", $con);
$encryptedpassword = md5($_POST['uPassword']);
$sql="INSERT INTO users (uName, uPassword, uSurname, uFirstName)
VALUES
('$_POST[uName]','$encryptedpassword','$_POST[uSurname]','$_POST[uFirstName]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Account created. You can now login";
mysql_close($con)
?>
The closing of bracket is the issue in query
('$_POST[uName]','$encryptedpassword','$_POST[uSurname]','$_POST[uFirstName]'";
This needs a closing ' ) '

Related

How to fix "Array index out of range?"

When logging into my Unity project, I get error "Array index is out of range" at this line of my C# code
if (www.text[0] == '0')
www.text pulls from this php script (www.text is returning null when debugging so it must be an error with my script).
<?php
$con = mysqli_connect('localhost', 'root', 'root', 'unityaccess');
//check that connection happened
if (mysqli_connect_errno())
{
echo "1: Connection failed"; //error code #1 = connection failed
exit();
}
$username = $_POST["name"];
$password = $_POST["password"];
//check if name exists
$namecheckquery = "SELECT username, salt, hash, score FROM players WHERE
username = ' " . $username . "';";
$namecheck = mysqli_query($con, $namecheckquery) or die("2: Name check query
failed"); //error code #2 - name check query failed
if (mysqli_num_rows($namecheck) != 1)
{
echo "5: Either no user with name, or more than one";
exit();
}
//get login info from query
$existinginfo = mysqli_fetch_assoc($namecheck)
$salt= $existinginfo["salt"];
$hash = $existinginfo["hash"];
$loginhash = crypt($password, $salt);
if($hash != $loginhash)
{
echo "6: Incorrect password"; //error code #6 - password does not hash to
match table
exit();
}
echo "0\t" . $existinginfo["score"];
?>
I'm following a tutorial and am new to php and sql.
https://www.youtube.com/watch?v=NVdjlXgbiMM
In the tutorial his code is exactly the same as mine. Looking at it myself I would assume that the echo "0\t" . $existinginfo["score"]; is the problem, and that putting a tab isn't separating it into an array. In his code he runs it and it's fine though, so I must be missing something else?
You have a space after the ' in the query on this line:
$namecheckquery = "SELECT username, salt, hash, score FROM players WHERE
username = ' " . $username . "';";
So if the username entered is user1 it will look in the database for <space>user1 (where <space> means a space character). Remove that space.
$namecheckquery = "SELECT username, salt, hash, score FROM players WHERE
username = '" . $username . "';";
Actually, it would be even better if you learned to use prepared statements, then problems like this are nearly impossible, as well as making the code safe from SQL-injection. Read How can I prevent SQL injection in PHP?

PHP - login-function using sha1 hashed password, can't get it to work

for a college project I need to create a simple registration and login function. We are required to hash the password using sha1 (I know its not secure), and add a specific salt at the start of the password. Data is being stored in a mySQL database. The registration.php seems to be working out, but I'm having trouble comparing the password from the html form to the password stored in the database. Been googling for a day now, but I am only finding login-functions using the password_verify() function, which doesn't seem to work with sha1. Apologies if the solution or obvious, VERY new to php.
Didn't include my connection-part of the code, it's working as intended. no matter what I input in the fields in the html-form, I get the "invalid username or password" output no matter what.
$formUsername = mysqli_real_escape_string($connect, $_REQUEST['username']);
$formPassword = mysqli_real_escape_string($connect, $_REQUEST['password']);
$sql = "SELECT passord FROM bruker WHERE brukerNavn = '$formUsername';";
$passwordFraDatabase = mysqli_query($connect, $sql);
$row = mysqli_fetch_assoc($passwordFraDatabase);
$passordSomString = $row['passord'];
$salt = 'IT2_2018';
$passwordFraForm = sha1($salt . $formPassword);
if ($passwordFraForm == $passordSomString) {
echo("Logged in");
}
else echo("invalid username or password");
Edit: To those saying I shouldn't use sha1, read the entire question, I specifically said I was required to use sha1, its a college project.
Since someone asked, this is how the password is registered in the first place:
$email = mysqli_real_escape_string($connect, $_REQUEST['email']);
$username = mysqli_real_escape_string($connect, $_REQUEST['username']);
$password = mysqli_real_escape_string($connect, $_REQUEST['password']);
$salt = 'IT2_2018';
$securepassword = sha1($salt . $password);
$sql = "INSERT INTO bruker (ePost, brukerNavn, passord) VALUES ('$email', '$username', '$securepassword')";
if(mysqli_query($connect, $sql)){
echo "user registered!";
} else{
echo "could not register user " . mysqli_error($connect);
}
In Php default compare function (strcmp) and (==) operator both can compare maximum of 32bit character string.
So more than 32bit character string must be compared using (strncmp) function.
In your case as you using sha1 which producing 160bit string thats why it is not working.
So use strncmp(str1,str2,maximum_length_want_to_compare);
In your case it will be
if (strncmp($passwordFraForm, $passordSomString,160)==0){ echo("Logged in"); } else echo("invalid username or password");

MySqli adding multiple rows to db

I'm sending data to a db from a web form but every time I run it the data is stored in the db in six new rows rather than just one.
The form is just a standard form with inputs for email/password and a submit button. The action of the form runs this:
<?php
// connect to db
$link = new mysqli("localhost", "root", "", "db_name");
if (!$link) {die('Database Error: Could not connect: ' . mysql_error());}
// username and password sent from form
$email = $_POST['email'];
$password = ($_POST['password']);
// encrypt
$salt = substr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), 0, 16);
$em = crypt($email, '$6$'.$salt);
$pw = crypt($password, '$6$'.$salt);
// insert to db
$insert = "INSERT INTO users (email, password) VALUES ('$em', '$pw')";
$link -> query($insert);
// check succes/fail
if ($link->query($insert) === TRUE) {
echo "New record created successfully";}
else {
echo "Error: " . $sql . "<br>" . $link->error;
}
// close the db connection
$link->close();
I know this brings up a question about sanitizing inputs with encryption/salting. This page says that it's a reasonable method. Please feel free to bring that up, but I'm not really looking for an argument over best practices for sanitizing user inputs.
I'm wondering if anyone cal tell me why the data would be stored 6 times instead of just once. I changed the $6$ to $1$ but it still added 6 rows.
You have some silly seo-friendly links implementation on your site that makes it run your php code on every reques, and 5 links to non-existent resources in your html.

my registration form details are not getting in the database (phpmyadmin)

Whenever I try any new registration it creates the user but no information is fed into the database
database name is chatbox
and table name is users
<?php
if (isset($_POST['submit'])){
$con = mysql_connect('localhost','root','');
mysql_select_db('chatbox',$con);
$uname = $_POST['username'];
$pword = $_POST['password'];
$pword2 = $_POST['password2'];
if($pword != $pword2){
echo "Passwords do not match. <br>";
}
else {
$checkexist = mysql_query("SELECT username FROM users WHERE username='$uname'");
if (mysql_num_rows($checkexist)){
echo "<center>";
echo "Username already exists, Please select different username<br>";
echo "</center>";
}
else {
mysql_query("INSERT INTO users ('username','password') VALUES ('$uname','$pword')");
echo "<center>";
echo "You have successfully registered. Click <a href='index.php'>here</a> to go start chat<br>";
echo "</center>";
}
}
}
Firstly, you should have a look at mysqli http://php.net/manual/en/book.mysqli.php it's the 'improved' version of mysql, and mysql is now deprecated as of php 5.5
Anyway, to help diagnose, you can use 'or die', to output a message if your script was unsuccessful.
$con = mysql_connect('localhost','root','') or die("could not connect");
mysql_select_db('chatbox',$con) or die("could not select db");
if you're saving users' passwords in a database, you should definitely look into encrypting them, see: http://php.net/manual/en/faq.passwords.php to begin with.
Janaka is right, in your insert statement, either use backticks for the fields `` or don't use any kind of quotes at all (username, password)
There is a little unfamiliarity with your sql query. Try this.
INSERT INTO users (`username`,`password`) VALUES ('$uname','$pword')

Values are not being added to the database

I am very new to PHP and Mysql. I have made a registeration form but the values being inputted are not being saved in my database. I don't know why. I am connected to the database. Could anyone give me some insight? By the way, I know you are going to say "Mysql" is deprecated. But I am just starting out and learning how all of this works. As soon as I have a thorough understanding of the processes I am going to change my code to Mysqli...
<?php
//form data
$submit = strip_tags($_POST['submit']);
$fname = strip_tags($_POST['fname']);
$lname = strip_tags($_POST['lname']);
$usernamereg = strip_tags($_POST['usernamereg']);
$passwordreg = strip_tags($_POST['passwordreg']);
$email = strip_tags($_POST['email']);
$emailcheck = strip_tags($_POST['emailcheck']);
$date = date("Y-m-d");
if($submit)
{
//check for existence
if($fname&&$lname&&$usernamereg&&$passwordreg&&$email&&$emailcheck)
{
//encrypt password
$password = md5($passwordreg);
if(strlen($usernamereg)>25)
{
echo "Username must be 25 characters or less.";
}
else
{
//checks password length
if(strlen($passwordreg)<6)
{
echo "Passwords must be atleast 6 characters long";
}
else
{
if($email!=$emailcheck)
{
echo "emails to not match";
}
else
{
//open database
$connect = mysql_connect("localhost","root","clandestine");
mysql_select_db("user_db"); //selects database
$queryreg = mysql_query("INSERT INTO users VALUES('','$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck'");
echo "You have been registered!";
}
}
}
}
else
echo "Please fill in <b>all</b> fields!";
Try assigning the columns in the INSERT query.
$queryreg = mysql_query("INSERT INTO users (`randomField`, `date`, `first_name`, `last_name`, `username`, `password`, `email`, `email_check`) VALUES ('','$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck'");
What is the first column supposed to be?
Have you done any sanity checking? (ie, printing test data to the screen at certain points in the code to make sure your IF statements are evaluating to true?
Additionally, try saving your INSERT query as a variable string:
$query = "INSERT INTO.............";
and then printing it to the screen. Copy and paste that query into PHPMyAdmin (if you have access to it) and see if there are any errors with your statement. PMA will tell you what errors there are, if any.
EDIT: Also, please don't ever MD5 a password or other highly sensitive data. Use a secure algorithm and salt the password. If you're unsure of what this all means:
refer to this link
What do you get if you do:
$query = "INSERT INTO users
(date, first_name, last_name, username, password, email, email_check)
VALUES
('$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck')";
mysql_query($query)or die('Error: <br />'.$query.'<br />'.mysql_error());
Note the removal of the backticks was just to simplify the code. It's correct to leave them in but with no spaces etc in your column names it should work anyway. Oh, and this is NOT good practice for production, of course. Just really clear debug.

Categories