Jump to content

PHP wont encrypt passwords


Tom8001
Go to solution Solved by QuickOldCar,

Recommended Posts

This is my code it's not working.

$username = $_POST['username'];


        $password = $_POST['password'];
        $encrypt_password = md5($password);

        $email = $_POST['email'];


        $usrsql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$encrypt_password'";

//--> Below is the INSERT Code

$query = "INSERT INTO `x_users` (username, password, email) VALUES ('$username', '$encrypt_password', '$email')";

        $result = mysql_query($query);

        if($result == 1) {

            print("Thank you, your accout has been created!");
        }

Can anyone tell me why the md5() function is not working?

Edited by Tom8001
Link to comment
Share on other sites

Okay i do only see a part of a user registration process and not of a login .

 

Your code is not secured for sql injection. (google it)

 

if a user wants to log in he will enter his username and password into a login form. When the form has been sent your php script have to compare username and password to the usernames and password available into the database.

 

In the database are only encrypted passwords. so you need to compare an encrypted password to another encrypted password or they will never be equal. THerefore you have to encrypt the password that has been sent through the form first before you compare it to the passwords into the database.

 

If you nee more help, please post the part that handles your login form.

Link to comment
Share on other sites

  • Solution

What your code should do:

 

check if POST is set

if(isset($_POST){
//proceed with code
} else {
//show a message,any errors,redirects or a form
}

assign variables to POST values only if they exist

trimming the unseen whitespace as well with trim() (if a password has whitespace at the ends would become a different hash)

checking for empty or blank values

if(isset($_POST['username']) && trim($_POST['username']) != ''){
$username = trim($_POST['username']);
}

checking what type of data the value is

character type checking

filter validation

filter functions

sanitize

 

email example

if(isset($_POST['email']) &&  filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL)){
$email = trim($_POST['email']);
}

as Frank said you compare 2 encrypted passwords, one encrypted from the form value and the saved one in database

don't use md5() but something like password_hash()

 

don't use outdated mysql_* functions, use mysqli_* or pdo

 

check/sanitize/filter then escape anything you are using in a mysql query

mysqli_real_escape_string() or prepared statements

 

before you try and do anything with the database, ensure that all your variables exist, not empty, data you expect and escaped

 

it's nice to incorporate error handling to assist you and your users as to whats going on

can create an error array or messages upon any errors throughout your script

 

error reporting

While you are creating code add this to the top of your php script

error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', '1');

later on set it to log errors or not show errors a production site

error_reporting(0);
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");//or can look default folder
Link to comment
Share on other sites

I have SQL Injection code in the login script but not registration and i already have & i always use error_reporting(E_ALL | E_NOTICE);

error_reporting(E_ALL | E_NOTICE);

Here's my login

<?php

error_reporting(E_ALL | E_NOTICE);

require 'connect.php';

session_start();

if(isset($_POST['submit'])) {

	$username = $_POST['username'];
	$password = md5($_POST['password']);

	if(empty($username)) {

            echo "You did not enter a username, Redirecting...";

            echo "<meta http-equiv='refresh' content='2' URL='login.php'>";

            exit();

        } else if(empty($password)) {

            echo "You did not enter a password, Redirecting...";

            echo "<meta http-equiv='refresh' content='2' URL='login.php'>";

            exit();


} 

	//Prevent hackers from using SQL Injection to hack into Database
	$md5_password = md5($_POST['password']);
	$username = stripslashes($username);
	$password = stripslashes($password);
	$username = mysql_real_escape_string($username);
	$password = mysql_real_escape_string($password);


	$sql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$encrypt_password'";
	$result = mysql_query($sql);
	$count = mysql_num_rows($result);
	$row = mysql_fetch_assoc($result);
	$user_level = $row['user_level'];


	if($count == 1) {

		$_SESSION['loggedIn'] = true;
		$_SESSION['username'] = $_POST['username'];

	} else {

		print("<br> <br>Username / Password is Incorrect!");

		exit();

	}
Edited by Tom8001
Link to comment
Share on other sites

 

What your code should do:

 

check if POST is set

if(isset($_POST){
//proceed with code
} else {
//show a message,any errors,redirects or a form
}

assign variables to POST values only if they exist

trimming the unseen whitespace as well with trim() (if a password has whitespace at the ends would become a different hash)

checking for empty or blank values

if(isset($_POST['username']) && trim($_POST['username']) != ''){
$username = trim($_POST['username']);
}

Why do i need to add these? I'm still new to PHP im just curious i don't fully understand

 

Edited by Tom8001
Link to comment
Share on other sites

It says this on PHP.net 

" " (ASCII 32 (0x20)), an ordinary space.
"\t" (ASCII 9 (0x09)), a tab.
"\n" (ASCII 10 (0x0A)), a new line (line feed).
"\r" (ASCII 13 (0x0D)), a carriage return.
"\0" (ASCII 0 (0x00)), the NUL-byte.
"\x0B" (ASCII 11 (0x0B)), a vertical tab.

But i don't understand what they are

Link to comment
Share on other sites

if(isset($_POST){

 

 

this is wrong advice. the $_POST array is always set by php. all the super-global arrays are set, even if they are empty.

 

to detect if a post method form has been submitted, you either need to test if a specific, non-optional/non-disabled, field in the form is set, which your code is doing with the if(isset($_POST['submit'])) {, provided you always click on the submit button to submit the form, or you can test if $_SERVER['REQUEST_METHOD'] == 'POST' if all you want to detect is if any post method form was submitted.

 

once you have detected that a form has been submitted, you don't need to individually test if text/password/textarea fields are set, they will be if you don't have any coding errors in your form. and in fact, if you do have coding errors, you wouldn't want to use isset() to qualify the references to those type of fields as it would hide the fact that your form doesn't have fields by those expected names.

Link to comment
Share on other sites

I Used the code below & The script works fine with that, but my only problem now is encrypting my passwords i can't get it to work, when they register it goes into the database as md5() but when trying to login it says username or password is incorrect.

if (isset($_POST['username']) && isset($_POST['password'])){
Edited by Tom8001
Link to comment
Share on other sites

You mean the advice didn't work?

 

trimming post values didn't work?

 

You know that's going to be as secure as just checking if the password is bobby?

Little overboard, but not that far off.

 

$md5_password = md5(trim($_POST['password']));

 

$sql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$md5_password'";

Link to comment
Share on other sites

You don't need stripslashes, mysql_real_escape_string does that

 

Be sure to trim on both registration and your login.

 

grr were doing it 2x

$username = $_POST['username'];
$password = md5($_POST['password']);

 

Just this

$username = mysql_real_escape_string(trim($_POST['username']));
$md5_password = md5(trim($_POST['password']));
$password = mysql_real_escape_string($md5_password);

If this don't work tom, post both your current register and login forms.

Edited by QuickOldCar
Link to comment
Share on other sites

Login script

<?php

error_reporting(E_ALL | E_NOTICE);

require 'connect.php';

session_start();

if(isset($_POST['submit'])) {

	$username = $_POST['username'];
	$password = $_POST['password'];

	if(empty($username)) {

            echo "You did not enter a username, Redirecting...";

            echo "<meta http-equiv='refresh' content='2' URL='login.php'>";

            exit();

        } else if(empty($password)) {

            echo "You did not enter a password, Redirecting...";

            echo "<meta http-equiv='refresh' content='2' URL='login.php'>";

            exit();


} 

	//Prevent hackers from using SQL Injection to hack into Database
	$md5_password = md5(trim($_POST['password']));
	$username = mysql_real_escape_string($username);
	$password = mysql_real_escape_string($password);


	$sql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'";
	$result = mysql_query($sql);
	$count = mysql_num_rows($result);
	$row = mysql_fetch_assoc($result);
	$user_level = $row['user_level'];


	if($count == 1) {

		$_SESSION['loggedIn'] = true;
		$_SESSION['username'] = $_POST['username'];

	}

Registration script

<?php

    error_reporting(E_ALL | E_NOTICE);
	
    require 'connect.php';

    echo "<title>  Register  </title>";

    if(isset($_POST['submit'])) {

    if (isset($_POST['username']) && isset($_POST['password'])){


        $username = $_POST['username'];


        $password = $_POST['password'];


        $email = $_POST['email'];
        $username = mysql_real_escape_string($username);
        $email = mysql_escape_string($email);
        $password = mysql_real_escape_string($password);


        $usrsql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$md5_password'";

        $usrres = mysql_query($usrsql);

        if (!$usrres)

        {

        die("Query Failed.");

        }

        if (mysql_num_rows($usrres) > 0) {

            echo "<style>body {background-image: url('http://desktopwallpapers.biz/wp-content/uploads/2014/09/Website-Background-Cool-HD.jpg');} #uexist {position: fixed;top: 200px;left: 550px; font-size: 24px;}</style>";

            die("<font color='yellow' face='Tahoma'> <b> <center> <p id='uexist'> The username you entered is already in use. </p> </center> </b> </font>");

        } else {

            // DO NOTHING
        }

        if(empty($username)) {

            print("<font color='red'>You did not enter a username!</font>   <br> <br>");

        } else if(empty($password)) {

            die("<font color='red'>You did not enter a password!</font>");

        } if(strlen($username)<3) {

            die("<font color='red'>Your username must be over 3 characters!</font>");

        } else if(strlen($username)>20) {

         die("<font color='red'>Your username is over 20 characters and must be under! usernames are 3 - 20 characters!</font>");
        
        } if(isset($_POST['email']) && filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL)) {

            $email = trim($_POST['email']);
        }

        $md5_password = md5(trim($_POST['password']));

        $query = "INSERT INTO `x_users` (username, password, email) VALUES ('$username', '$md5_password', '$email')";

        $result = mysql_query($query);

        if($result == 1) {

            print("Thank you, your accout has been created!");

        }

    }

}

    ?>
Link to comment
Share on other sites

login

<?php
error_reporting(E_ALL | E_NOTICE);

require 'connect.php';

session_start();

if (isset($_POST['submit'])) {
   
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
   
    if (empty($username)) {
       
        echo "You did not enter a username, Redirecting...";
       
        echo "<meta http-equiv='refresh' content='2' URL='login.php'>";
       
        exit();
       
    }
   
    if (empty($password)) {
       
        echo "You did not enter a password, Redirecting...";
       
        echo "<meta http-equiv='refresh' content='2' URL='login.php'>";
       
        exit();
       
    }
   
    //Prevent hackers from using SQL Injection to hack into Database
    $username     = mysql_real_escape_string($username);
    $md5_password = md5($password);
    $password     = mysql_real_escape_string($md5_password);
   
   
    $sql        = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'";
    $result     = mysql_query($sql);
    $count      = mysql_num_rows($result);
    $row        = mysql_fetch_assoc($result);
    $user_level = $row['user_level'];
   
   
    if ($count == 1) {
       
        $_SESSION['loggedIn'] = true;
        $_SESSION['username'] = $_POST['username'];
       
    }
   
}
?>

register

 <?php

error_reporting(E_ALL | E_NOTICE);

require 'connect.php';

echo "<title>  Register  </title>";

if (isset($_POST['submit'])) {
    
    if (isset($_POST['username']) && isset($_POST['password'])) {
        
        
        $username = trim($_POST['username']);
        
        $password = trim($_POST['password']);
        
        
        $email        = $_POST['email'];
        $username     = mysql_real_escape_string($username);
        $email        = mysql_real_escape_string($email);
        $md5_password = md5($password);
        $password     = mysql_real_escape_string($md5_password);
        
        /*
        why checking for a username and also a password?
        isn't this registration?
        don't you want just no duplicate names?
        */
        $usrsql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'";
        
        $usrres = mysql_query($usrsql);
        
        if (!$usrres) {
            
            die("Query Failed.");
            
        }
        
        if (mysql_num_rows($usrres) > 0) {
            
            echo "<style>body {background-image: url('http://desktopwallpapers.biz/wp-content/uploads/2014/09/Website-Background-Cool-HD.jpg');} #uexist {position: fixed;top: 200px;left: 550px; font-size: 24px;}</style>";
            
            die("<font color='yellow' face='Tahoma'> <b> <center> <p id='uexist'> The username you entered is already in use. </p> </center> </b> </font>");
            
        } else {
            
            // DO NOTHING
        }
        
        if (empty($username)) {
            
            print("<font color='red'>You did not enter a username!</font>   <br> <br>");
            
        } else if (empty($password)) {
            
            die("<font color='red'>You did not enter a password!</font>");
            
        }
        if (strlen($username) < 3) {
            
            die("<font color='red'>Your username must be over 3 characters!</font>");
            
        } else if (strlen($username) > 20) {
            
            die("<font color='red'>Your username is over 20 characters and must be under! usernames are 3 - 20 characters!</font>");
            
        }
        if (isset($_POST['email']) && filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL)) {
            
            $email = trim($_POST['email']);
        }
        
        
        $query = "INSERT INTO `x_users` (username, password, email) VALUES ('$username', '$password', '$email')";
        
        $result = mysql_query($query);
        
        if ($result == 1) {
            
            print("Thank you, your account has been created!");
            
        }
        
    }
    
}

?> 
Link to comment
Share on other sites

the only error i have is Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\xampp\htdocs\Login\connect.phpon line 15

 

& 

 

It still says username or password is incorrect when trying to login.

Link to comment
Share on other sites

you need to actually debug and find out why your script is not matching the username/password. just randomly throwing a bunch of code against the wall to see what sticks isn't programming and will take forever to get something that works.

 

you need to echo out the $sql query statement to see what exactly it is and then look in your database table, using your favorite database management tool, such as phpmyadmin, and see if the username and hashed password values, in the $sql variable that you echoed, exactly match the values in a row in your database table.

Link to comment
Share on other sites

you need to actually debug and find out why your script is not matching the username/password. just randomly throwing a bunch of code against the wall to see what sticks isn't programming and will take forever to get something that works.

 

you need to echo out the $sql query statement to see what exactly it is and then look in your database table, using your favorite database management tool, such as phpmyadmin, and see if the username and hashed password values, in the $sql variable that you echoed, exactly match the values in a row in your database table.

I'm new to PHP

Link to comment
Share on other sites

everyone that is reading this was new to php at one point in time.

 

does that mean you are not going to echo the $sql variable holding the query statement, look at it to see if it even has values in it, and then look at your database table and make sure you have a row with those exact same values? you are the only person here who has access to your server and can do these things to pin down where the problem is at.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.