Rehashing a password being changed PHP - php

I am currently having problems with hashing. Heres a bit of background;
The user creates an account, and their password is hashed using password_hash($password, PASSWORD_BCRYPT). Then, when they login, the password is checked via password_verify and if it is correct, they will be logged in.
However, when the user goes to their profile and edit's their details, changing their password, they can never login again. As well as this, if an employee changes the users password, they still cannot login.
I've been trying to look around and solve this but can't find anything, and what is the most wierd thing is that when an employee (lets say the admin account) changes another employees password, they can login fine with their new password? I've done pretty much the same code as the working changing password and rehashing code, but it still does not work.
Sign Up:
<?php
$servername = "localhost"; /*The host of the MySQL name.*/
$username = "root"; /*MySQL username.*/
$password = ""; /*MySQL password.*/
$dbname = ""; /*MySQL database name.*/
$tablename = "clientinformation"; /*The table name that will be used from the database.*/
/*This line check if the website can connect to the database, else it will return an error message.*/
mysql_connect("$servername", "$username", "$password")or die("Cannot connect to the database.");
/*This line checks if the website can select the database the website is requesting, else it will return an error message.*/
mysql_select_db("$dbname")or die("Cannot select the database.");
$clienttitle = $_POST["clienttitle"]; /*Retrieves the ClientTitle input from the user.*/
$clientforename = $_POST["clientforename"]; /*Retrieves the ClientForename input from the user.*/
$clientsurname = $_POST["clientsurname"]; /*Retrieves the ClientSurname input from the user.*/
$phonenumber = $_POST["phonenumber"]; /*Retrieves the PhoneNumber input from the user.*/
$clientusername = $_POST["clientusername"]; /*Retrieves the Username input from the user.*/
$clientpassword = $_POST["clientpassword"]; /*Retrieves the ClientPassword input from the user.*/
$emailaddress = $_POST["emailaddress"]; /*Retrieves the EmailAddress input from the user.*/
$billingaddress = $_POST["billingaddress"]; /*Retrieves the BillingAddress input from the user.*/
/*Here, each of the inputs are put through the 'stripslashes' function, which stops a MySQL injection attack.*/
$clienttitle = stripslashes($clienttitle);
$clientforename = stripslashes($clientforename);
$clientsurname = stripslashes($clientsurname);
$phonenumber = stripslashes($phonenumber);
$clientusername = stripslashes($clientusername);
$clientpassword = stripslashes($clientpassword);
$emailaddress = stripslashes($emailaddress);
$billingaddress = stripslashes($billingaddress);
/*The use of mysql_real_escape_string also stops a MySQL injection attack.*/
$clienttitle = mysql_real_escape_string($clienttitle);
$clientforename = mysql_real_escape_string($clientforename);
$clientsurname = mysql_real_escape_string($clientsurname);
$phonenumber = mysql_real_escape_string($phonenumber);
$clientusername = mysql_real_escape_string($clientusername);
$clientpassword = mysql_real_escape_string($clientpassword);
$emailaddress = mysql_real_escape_string($emailaddress);
$billingaddress = mysql_real_escape_string($billingaddress);
$hashedclientpassword = password_hash($clientpassword, PASSWORD_BCRYPT);
$query = "INSERT INTO $tablename (ClientID, ClientTitle, ClientForename, ClientSurname, PhoneNumber, Username, EmailAddress, ClientPassword, BillingAddress, SignUpDate)VALUES(NULL, '$clienttitle', '$clientforename', '$clientsurname', '$phonenumber', '$clientusername', '$emailaddress', '$hashedclientpassword', '$billingaddress', CURRENT_TIMESTAMP)";
$result = mysql_query($query);
if($result){
echo "Successful";
header("location:Index.php");
} else {
echo ("Unsuccessful : " . mysql_error());
}
mysql_close();
?>
Check Login:
<?php
$servername = "localhost"; /*The host of the MySQL name.*/
$username = "root"; /*MySQL username.*/
$password = ""; /*MySQL password.*/
$dbname = ""; /*MySQL database name.*/
$tablename = "clientinformation"; /*The table name that will be used from the database.*/
/*This line check if the website can connect to the database, else it will return an error message.*/
mysql_connect("$servername", "$username", "$password")or die("Cannot connect to the database.");
/*This line checks if the website can select the database the website is requesting, else it will return an error message.*/
mysql_select_db("$dbname")or die("Cannot select the database.");
/*This retrieves the data inserted by the user from the previous page. In this case, it is retrieving the username and password the user entered.*/
$userusername = $_POST["Username"];
$userpassword = $_POST["ClientPassword"];
/*Here, these four lines of code are used to stop an MySQL injection attack on the website/database.*/
$userusername = stripslashes($userusername);
$userpassword = stripslashes($userpassword);
$userusername = mysql_real_escape_string($userusername);
$userpassword = mysql_real_escape_string($userpassword);
$sql = "SELECT ClientPassword FROM $tablename WHERE Username = '$userusername'";
$result = mysql_query($sql);
$datarow = mysql_fetch_array($result);
$hasheduserpassword = $datarow['0'];
if (password_verify($userpassword, $hasheduserpassword)) {
session_start();
$_SESSION['Username'] = $userusername;
$_SESSION['ClientPassword'] = $hasheduserpassword;
header("Location:IndexUserLogin.php");
} else {
header("location:WrongPU.php");
}
?>
user editing their details:
<?php
session_start();
if(! $_SESSION['Username']) {
header("location:Index.php");
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "";
$tablename = "clientinformation";
mysql_connect("$servername", "$username", "$password") or die("Cannot connect to the database.");
mysql_select_db("$dbname") or die ("Cannot select the database.");
$clientid = $_POST["clientid"];
$clienttitle = $_POST["clienttitle"];
$clientforename = $_POST["clientforename"];
$clientsurname = $_POST["clientsurname"];
$phonenumber = $_POST["phonenumber"];
$clientusername = $_POST["clientusername"];
$emailaddress = $_POST["emailaddress"];
$clientpassword = $_POST["clientpassword"];
$billingaddress = $_POST["billingaddress"];
$clientid = stripslashes($clientid);
$clienttitle = stripslashes($clienttitle);
$clientforename = stripslashes($clientforename);
$clientsurname = stripslashes($clientsurname);
$phonenumber = stripslashes($phonenumber);
$clientusername = stripslashes($clientusername);
$emailaddress = stripslashes($emailaddress);
$clientpassword = stripslashes($clientpassword);
$billingaddress = stripslashes($billingaddress);
$clientid = mysql_real_escape_string($clientid);
$clienttitle = mysql_real_escape_string($clienttitle);
$clientforename = mysql_real_escape_string($clientforename);
$clientsurname = mysql_real_escape_string($clientsurname);
$phonenumber = mysql_real_escape_string($phonenumber);
$clientusername = mysql_real_escape_string($clientusername);
$emailaddress = mysql_real_escape_string($emailaddress);
$clientpassword = mysql_real_escape_string($clientpassword);
$billingaddress = mysql_real_escape_string($billingaddress);
$hashedclientpassword = password_hash($clientpassword, PASSWORD_BCRYPT);
$query = "UPDATE $tablename SET ClientTitle = '$clienttitle', ClientForename = '$clientforename', ClientSurname = '$clientsurname', PhoneNumber = '$phonenumber', Username = '$clientusername', EmailAddress = '$emailaddress', ClientPassword = '$hashedclientpassword', BillingAddress = '$billingaddress' WHERE ClientID = '$clientid'";
$result = mysql_query($query);
if($result) {
echo "Successful update";
header("Location:UserCP.php");
} else {
echo ("ERROR : " . mysql_errno . " " . mysql_error());
}
?>
Edit employees details (works)
<?php
session_start();
if($_SESSION['EmployeeUsername'] !== "Admin") {
header("location:Index.php");
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "";
$tablename = "employeelogin";
mysql_connect("$servername", "$username", "$password") or die("Cannot connect to the database.");
mysql_select_db("$dbname") or die ("Cannot select the database.");
$employeeid = $_POST['employeeid'];
$employeeusername = $_POST['employeeusername'];
$employeepassword = $_POST['employeepassword'];
$employeename = $_POST['employeename'];
$employeesurname = $_POST['employeesurname'];
$employeeid = stripslashes($employeeid);
$employeeusername = stripslashes($employeeusername);
$employeepassword = stripslashes($employeepassword);
$employeename = stripslashes($employeename);
$employeesurname = stripslashes($employeesurname);
$employeeid = mysql_real_escape_string($employeeid);
$employeeusername = mysql_real_escape_string($employeeusername);
$employeepassword = mysql_real_escape_string($employeepassword);
$employeename = mysql_real_escape_string($employeename);
$employeesurname = mysql_real_escape_string($employeesurname);
$hashedemployeepassword = password_hash($employeepassword, PASSWORD_BCRYPT);
$query = "UPDATE $tablename SET EmployeeID = '$employeeid', EmployeeUsername = '$employeeusername', EmployeePassword = '$hashedemployeepassword', EmployeeName = '$employeename', EmployeeSurname = '$employeesurname' WHERE EmployeeID = '$employeeid'";
$result = mysql_query($query);
if($result) {
echo "Successful update";
header("Location:EmployeeCP.php");
} else {
echo ("ERROR : " . mysql_errno . " " . mysql_error());
}
?>
Check employees login (work)
<?php
$servername = "localhost"; /*The host of the MySQL name.*/
$username = "root"; /*MySQL username.*/
$password = ""; /*MySQL password.*/
$dbname = ""; /*MySQL database name.*/
$tablename = "employeelogin"; /*The table name that will be used from the database.*/
/*This line check if the website can connect to the database, else it will return an error message.*/
mysql_connect("$servername", "$username", "$password")or die("Cannot connect to the database.");
/*This line checks if the website can select the database the website is requesting, else it will return an error message.*/
mysql_select_db("$dbname")or die("Cannot select the database.");
/*This retrieves the data inserted by the user from the previous page. In this case, it is retrieving the username and password the employee entered.*/
$employeeusername = $_POST["EmployeeUsername"];
$employeepassword = $_POST["EmployeePassword"];
/*Here, these four lines of code are used to stop an MySQL injection attack on the website/database.*/
$employeeusername = stripslashes($employeeusername);
$employeepassword = stripslashes($employeepassword);
$employeeusername = mysql_real_escape_string($employeeusername);
$employeepassword = mysql_real_escape_string($employeepassword);
$sql = "SELECT EmployeePassword FROM $tablename WHERE EmployeeUsername = '$employeeusername'";
$result = mysql_query($sql);
$datarow = mysql_fetch_array($result);
$hashedemployeepassword = $datarow['0'];
if (password_verify($employeepassword, $hashedemployeepassword)) {
session_start();
$_SESSION['EmployeeUsername'] = $employeeusername;
$_SESSION['EmployeePassword'] = $hashedemployeepassword;
header("Location:IndexEmployeeLogin.php");
} else {
header("location:WrongPU.php");
}
?>
Cheers for all and any responses

Remove all calls to stripslashes() and mysql_real_escape_string() for password input, the functions password_hash() and password_verify() accept even binary input and are not prone to SQL-injection. I assume this already solves your problem.
Escaping should be done as late as possible and only for the given target system, so the function mysqli_real_escape_string() should only be called to build an SQL query.
Check wheter in both tables (clientinformation and employeelogin), the password-hash field is declared with 60 characters or more.
If this doesn't solve your problem, i would use UTF-8 for all your pages. You can check your pages with this W3C checker, every page should be stored in the UTF-8 file format and define the UTF-8 header.
Test with isset whether a variable exists: if(!isset($_SESSION['Username']))
The password hash should not be stored in the session, but maybe this is only for testing purposes.
Setting the userid is not necessary: "UPDATE $tablename SET EmployeeID = '$employeeid', ... WHERE EmployeeID = '$employeeid'";
And it is a good habit to always call exit after a redirect:
header('Location: Index.php', true, 303);
exit;

Related

Mysql not connecting to server through php

I have been trying to connect to the mysql server through php code, but was unable to. Please help me solve this problem.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$email = mysql_real_escape_string($_POST['email']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$bool = true;
mysql_connect("localhost", "root","rot_darshan") or die("Cannot connect to server"); //Connect to server
mysql_select_db("first_db") or die("Cannot connect to database"); //Connect to database
$query = mysql_query("Select * from users"); //Query the users table
while($row = mysql_fetch_array($query)) //display all rows from query
{
$table_users = $row['username']; // the first username row is passed on to $table_users, and so on until the query is finished
if($username == $table_users) // checks if there are any matching fields
{
$bool = false; // sets bool to false
Print '<script>alert("Username has been taken!");</script>'; //Prompts the user
Print '<script>window.location.assign("register.php");</script>'; // redirects to register.php
}
}
if($bool) // checks if bool is true
{
mysql_query("INSERT INTO users (username, password,fname,lname,email) VALUES ('$username','$password','$fname','$lname','$email')"); //Inserts the value to table users
Print '<script>alert("Successfully Registered!");</script>'; // Prompts the user
Print '<script>window.location.assign("register.php");</script>'; // redirects to register.php
}
}
?>
Please avoid the native mysql_* functions. These are depricated and will be removed:
http://php.net/manual/en/function.mysql-connect.php
Try to follow (mysqli_*):
https://www.w3schools.com/php/php_mysql_connect.asp
$servername = "localhost";
$username = "root";
$password = "rot_darshan";
$database = "first_db";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//Query example
$result = $conn->query("SELECT * FROM users")
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["username"]);
}
If these don't work, check your database credentials (username, password, database name and/or port)
Check for username,password by externally connecting .also replace localhost with 127.0.0.1 or your lan ip.
Check SELECT User, Host FROM mysql.user;

Database connect undefined

I'm getting an error saying Undefined variable: con,
the connection of the database is on the other php file, (include() is already on top of the code). I just don't know how to call the $con
if (isset($_POST['update_profile']))
{
if (isset($_POST['first_name']))
{
$first_name = mysqli_real_escape_string($con, $_POST['first_name']);
$sql = mysqli_query($con, "UPDATE tbl_fbusers SET fname = '$first_name' WHERE email = '$email_to_connect'");
}
if (isset($_POST['last_name']))
{
$last_name = mysqli_real_escape_string($con, $_POST['last_name']);
$sql = mysqli_query($con, "UPDATE tbl_fbusers SET lname = '$last_name' WHERE email = '$email_to_connect'");
}
if (isset($_POST['contact']))
{
$contact = mysqli_real_escape_string($con, $_POST['contact']);
$sql = mysqli_query($con, "UPDATE tbl_fbusers SET contact = '$contact' WHERE email = '$email_to_connect'");
}
}
here is the other php file
class Users {
public $table_name = 'tbl_fbusers';
function __construct(){
//database configuration
$dbServer = 'localhost'; //Define database server host
$dbUsername = 'root'; //Define database username
$dbPassword = ''; //Define database password
$dbName = 'db_zalian'; //Define database name
//connect databse
$con = mysqli_connect($dbServer,$dbUsername,$dbPassword,$dbName);
if(mysqli_connect_errno()){
die("Failed to connect with MySQL: ".mysqli_connect_error());
}else{
$this->connect = $con;
}
}
Thanks!
Defining $con as a GLOBAL variable is a terrible idea...
I suggest to make a file (eg. connection.php) that will contain the $con variable that is not in a function, and then include the connection.php to your other php files. It's more secure and easier, and you won't get to any troubles.
Since you have a class you need to initialize user class.
$user = new Users();
and then
$con = $user->connect;
Here you can run your sql like:
$contact = mysqli_real_escape_string($con, $_POST['contact']);
$sql = mysqli_query($con, "UPDATE tbl_fbusers SET contact =......... etc.
you need to define $con as global:
global $con
$con = mysqli_connect($dbServer,$dbUsername,$dbPassword,$dbName);

Reducing MSQL Query to a specific session

Using the code below, I was able to display each username and trial 1/0 flag in the table. What I want to do is display the data only for the existing user so I can say something like "Hello USERNAME, you have TRIAL access..." etc...
We're using standard HTACESS as the un/pass to enter the info area.
What needs to change here to only show the existing user's session?
<?PHP
$user_name = "blahblahblah";
$password = "blahblahblah";
$database = "blahblahblah";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM member_auth";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_array($result) ) {
print $db_field['username'] . " : ";
print $db_field['trial'] . " <br> ";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
please don't use mysql_ functions.. look into PDO or MySQLi here: http://www.phptherightway.com/#databases
Update your query to only return specific user results.
Using Form POST:
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);
Using URL Parameters:
$username = mysql_real_escape_string($_GET["username"]);
$password = mysql_real_escape_string($_GET["password"]);
So your SQL query will now look like:
$SQL = "SELECT * FROM member_auth WHERE username = '" . $username . "' AND password = '" . $password . "'";

New $_SESSION variable not created after query?

I'm trying to build a login process where, by using $_SESSION variables, the login credentials of the user are stored and used to show their relevant data from the database on screen (i.e. they will only see the school data that they work for).
<?php
session_start();
if(!isset($_SESSION['Initials'], $_SESSION['Surname']))
{
$host = "xxx";
$username = "xxx";
$password = "xxx";
$database_name = "xxx";
$table_name = "xxx";
mysql_connect($host, $username, $password) OR die("Can't
connect");
mysql_select_db($database_name) OR die("Can't connect to
Database");
$query = "SELECT Class FROM $table_name WHERE Initials = '".
$_SESSION['Initials']."' AND staff LIKE '%".$_SESSION['Surname']."'";
$result = mysql_query($query);
$class = mysql_fetch_array($result);
$count = mysql_num_rows($result);
if($count === NULL)
{
echo "ERROR";
}
else
{
$_SESSION['Class'] = $result;
echo "Class added to sessions";
}
}
?>
My initial problem where the query couldn't recognize the session variables was easily solved by adding the correct brackets for the if-statement. My next problem that has arisen here is that even though the query should be successfull (I don't receive an error message saying 'ERROR' when the $count is either FALSE or NULL) it's not creating the result array into a new session, because when I print the session array on a new page it's still only carrying over the 'Initials' and 'Surname' sessions.
What do I need to change to my query, or post-query process in order for that array (because it's bound to throw up multiple results) to be made into a new session?
Many thanks for the answers to my initial problem!
if(!isset($_SESSION['Initials'], $_SESSION['Surname'])) {
// code
}
u need { } brackets
if(!isset($_SESSION['Initials'], $_SESSION['Surname']))
$host = "xxxxx"; $username = "xxxxx"; $password = "xxxxx";
is
if(!isset($_SESSION['Initials'], $_SESSION['Surname'])) {
$host = "xxxxx";
}
$username = "xxxxx";
$password = "xxxxx";
I've found the answer - it turned out that I wasn't treating one of the session variables as a proper array and thus wouldn't load properly. I've added my script below so that people with similar problems in the future can use it as a reference point:
<?php
session_start();
// Server Details //
$host = "---";
$username = "---";
$password = "---";
$database_name = "---";
$table_name = "---";
// Connect Command //
mysql_connect($host, $username, $password) OR die("Can't
connect");
mysql_select_db($database_name) OR die("Can't connect to
Database");
// Query to call up the unique school name //
$query_school = mysql_query("SELECT DISTINCT School FROM $table_name
WHERE Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$result_school = mysql_result($query_school, 0);
// Query to call up the unique centre no //
$query_centreno = mysql_query("SELECT DISTINCT CentreNo FROM
$table_name WHERE Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$result_centreno = mysql_result($query_centreno, 0);
// The newly created sessions for school info //
$_SESSION['---'] = $result_school;
$_SESSION['---'] = $result_centreno;
// Query to call up the array of classes //
$query_class = mysql_query("SELECT Class FROM $table_name WHERE
Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$query_class__array = array();
while($row = mysql_fetch_assoc($query_class))
$query_class_array[] = $row;
$_SESSION['---'] = $query_class_array;
?>

Basic PHP-script doesn't work

I'm new to PHP and SQL but I'm trying to create a simple PHP-script that allows a user to login to a website. It doesn't work for some reason and I can't see why. Every time I try to login with the correct username & password, I get the error "Wrong Username or Password". The database-name and table-name are correct.
connect.php:
<?php
$db_host = 'localhost';
$db_name = 'app';
$db_user = 'root';
$db_pass = '';
$tbl_name = 'users';
// Connect to server and database
mysql_connect("$db_host", "$db_user", "$db_pass") or die("Unable to connect to MySQL.");
mysql_select_db($db_name)or die("Cannot select database.");
// Info sent from form
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
// Protection against MySQL injection
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$sql = ("SELECT * FROM $tbl_name WHERE username='$user' and password='$pass'");
$result= mysql_query($sql);
$count 0= mysql_num_rows($result);
if($count==1){
// Register $user, $pass send the user to "score.php"
session_register("user");
session_register("pass");
header("location:score.php");
}
else
{
echo "Wrong Username or Password";
}
?>
score.php:
<?php
session_start();
if(!session_is_registered(user)){
header("location:login.html");
}
?>
<html>
<body>
<h1>Login Successful</h1>
</body>
</html>
I hope someone can find my mistake, thanks!
FYI session_register and session_is_registered are deprecated and will be removed from PHP. Also try to change your code to use mysqli or PDO. Plenty of articles explain how to do it. Finally, make sure you escape input from the user ($_POST array) because you never know what the user will send and you don't want to be prone to SQL injections. You really do not want to store passwords in clear text, so using SHA1 or MD5 is best.
Having written the above, your code becomes (you can use the $_SESSION global array directly):
connect.php:
<?php
$db_host = 'localhost';
$db_name = 'app';
$db_user = 'root';
$db_pass = '';
$tbl_name = 'users';
// Connect to server and database
mysql_connect($db_host, $db_user, $db_pass) or die("Unable to connect to MySQL.");
mysql_select_db($db_name) or die("Cannot select database.");
// Info sent from form
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
// Protection against MySQL injection
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$sql = "SELECT * FROM $tbl_name "
. "WHERE username = '$user' "
. "AND password = sha1('$pass')";
$result = mysql_query($sql);
// There was an extra 0 here before the equals
$count = mysql_num_rows($result);
if ($count==1)
{
// Register $user, $pass send the user to "score.php"
$_SESSION['user'] = $user;
// You really don't need to store the password unless you use
// it somewhere else
$_SESSION['pass'] = $pass;
header("location: ./score.php");
}
else
{
echo "Wrong Username or Password";
}
?>
score.php:
<?php
session_start();
if (!isset($_SESSION['user']))
{
header("location:login.html");
}
?>
<html>
<body>
<h1>Login Successful</h1>
</body>
</html>
A couple of things
Change this line to the one with error checking i have put below it
$result= mysql_query($sql);
$result= mysql_query($sql) or die(mysql_error());
chances are there is an sql error and you are not picking it up, so the result will always have 0 rows
Also not sure if this line is a typo or not, there shouldn't be a 0 in there
$count 0= mysql_num_rows($result);

Categories