Comparing hash causing issues - php

I have a site that I am storing the username and hashed password in a table. I am trying to compair this information (username and hashed password) to the login information passed from my login site. Unfortunately this keeps crashing. If someone could point me in the right direction as to what I am doing wrong I would appreciate it. Below is the code I am using to check the login. It may be something very simple as I am still pretty new to php.
<?php
$myServer = "server.domain.com";
$myUser = "readaccess";
$myPass = "password";
$myDB = "database";
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
$selected = mssql_select_db($myDB, $dbhandle)
or die("Couldn't open database $myDB");
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
//declare the SQL statement that will query the database
$query = "SELECT password, salt ";
$query. = "FROM dbo.members ";
$query. = "WHERE username = '$myusername' ";
$result = mssql_query($query)
or die('A error occured: ' . mssql_get_last_message());
// SQL_num_row is counting table row
$count=mssql_num_rows($result);
if($count) < 1) //no such user exists
{
header('Location: main_login.php');
}
$userData = mssql_fetch_array($result, MSSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $mypassword) );
if($hash != $userData['password']) //incorrect password
{
header('Location: main_login.php');
}
else {
header('Location: index.php');
}
?>

I think the problem is this line
$result = mssql_query($query)
or die('A error occured: ' . mssql_get_last_message());
The proper way to check failure is
$result = mssql_query($query, $dbhandle);
if(!$result)
die('A error occured: ' . mssql_get_last_message());
Note that this goes for the mssql_connect and mssql_select_db statements as well.
Note that you need to provide the database resource to the mssql_query function.
Also, most people find it more readable if you use .= without a space between them. I don't think it produces a parse error, but it make a lot of sense to keep the whitespace out of the operand. (You wouldn't do $counter+ +; even if it were legal.)
Note for asking future questions, always include whatever error message you're seeing and, if it is referencing a line number, point out that line in your code sample. In this case, I don't think your problem has anything to do with hashing or sql, as it's entirely a parse/syntax error.

Related

My sql query is not executing on server with use session?

I have found record from login table but my mysql query is now executing.
following is my code.
$sqlQuery = "SELECT * FROM ".$table."
WHERE mobile_number='".$mobile_number."' AND
password='".base64_encode($password)."'";
// End
$select = mysql_query($sqlQuery);
$result = mysql_num_rows($select);
echo "<pre>Rest";
print_r($result);
It's always return 0 but same query is working in Phpmyadmin dashboard.
When i used mysql_error() function with mysql_query like following
$select = mysql_query($sqlQuery) or die ('Error updating database: '.mysql_error());
It's given error : Access denied for user ''#'localhost' (using password: NO)
Following is my connection code..
$dbname = "######";
$host = "localhost";
$user = "#####";
$password = "#####";
$connection = mysql_connect($host,$user,$password) or die("Error in database connection.");
if (!$connection)
{
return false;
}
if(!mysql_select_db($dbname, $connection))
{
return false;
}
I don't know why i faced the problem if anyone have idea about this pleas help me on this.
Thank You!!
Guess you gotta connect to your SQL Server with username and password. Error message says you didn’t even pass a username.
Simple example:
$link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
…
// do your stuff here
Please be sure to – at least – secure your parameters be escaping them with mysql_real_escape_string() for instance:
http://php.net/manual/en/function.mysql-real-escape-string.php
Or, even better, use PDO:
$stmt = $pdo->prepare('SELECT * FROM your_table WHERE mobile_number = :mobile_number');
$stmt->execute(array('mobile_number' => $mobile_number));
…
You should check the host, user name, and password in the configuration file and make sure that the information is consistent with the information given by the MySQL server administrator.
Reset the password and try it out:
Enter set password for 'root'#'localhost'=password(' your password ');Then restart the mysql service.Enter mysql-u root-p

PHP - Access Denied while passing parameters through URL

I made a php script which'll echo an image if the correct password is entered; so that, nobody can access the images stored on my server directly, thus, making my server more secure. Now, for the php script I used GET method to generate a mysql_query to my database in order to check if the email and password entered by the user are associated with a relevant account and then echo the image from a folder on my server. Now, in order to pass the parameters while runtime, I'm adding them in the URL like this:
http://<mywebserver>/get_image.php/?email=<email>&password=<password>&file_name=<image-file-name>
But, something's wrong with this whole setup, and I'm getting the following error:
Warning: mysql_query() [function.mysql-query]: Access denied for user
'uXXXXXXXXX'#'XX.XX.XX.XX' (using password: NO) in
/home/uXXXXXXXXX/public_html/get_image.php on line 11
Warning: mysql_query() [function.mysql-query]: A link to the server
could not be established in /home/uXXXXXXXXX/public_html/get_image.php
on line 11 Error getting data: Access denied for user
'uXXXXXXXXX'#'XX.XX.XX.XX' (using password: NO)
Here is my php script, get_image.php:
<?php
$file_path = "/ProfilePics/";
if(isset($_GET['email']) && isset($_GET['password']) && isset($_GET['file_name'])) {
$id = "\"" . $_GET['email'] . "\"";
$typed_password = "\"" . $_GET['password'] . "\"";
$file = $_GET['file_name'];
$result = mysql_query("SELECT * FROM students WHERE email = $id AND password = $typed_password") or die ("Error getting data: " . mysql_error()); //line 11
if(!empty($result)) {
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$user = array();
$user["email"] = $result["email"];
$user["password"] = $result["password"];
$pass = "\"" . $user["password"] . "\"";
if($pass == $typed_password) {
$img_path = $file_path . $file;
echo '<img src="' . $img_path . '" name = "cover" />';
} else {
echo "Incorrect password";
}
} else {
echo "Unable to find user";
}
} else {
echo "Unable to find user";
}
} else {
echo "Required field(s) is missing";
}
?>
I agree, that there are lots of other questions already on stackoverflow stating similar problems. But, I didn't find the solution(s) to those questions applicable for my code. So, any help on this will be highly appreciated. Thank you for your time!
This is because you have not connected your file get_image.php to your MySQL database. Do so as follows:
$host="localhost"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="database"; // Database name
$tbl_name="students"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
Simply replace the information above with the correct information.
You don't seem to be connecting to the database before you try to send queries to it.
It should like something like this:
$conn = new mysqli($servername, $username, $password, $dbname);
Taken from the example here:
http://www.w3schools.com/php/php_mysql_select.asp
Furthermore, if you care, you should consider using PDO or some other method of preventing SQL injection attacks.
SQL Injection:
https://en.wikipedia.org/wiki/SQL_injection
Information on PDO:
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
setup a database connection first:
$con = mysql_connect('server','username','password');
$rst = mysql_query('select...', $con);
remember that kind of library to access mysql is outdated.
imagine someone logging in with this password:
password = '"; DROP TABLE students;'
or something crafted better.
There are different libraries like PDO or MYSQLI that take cares of this for you.
in newer releases of php standard mysql libis deprecated and removed

I have the same error message when i put any error in the file

when I submit this form i have the same error message all the time . even if i put right or wrong password or don't put password or i write the name of the data base wrong . all of this wrongs i have the same error message :
Please enter a username and password .
so what is the problem . and i am sure about my fields on data base .
<?
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username && $password)
{
$connect = mysql_connect("localhsost","root","adminffpass") or die("Couldent connet to database ");
mysql_select_db("login") or die("No data base found ");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows !=0)
{
while ($row= mysql_fetch_array($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($username == $dbusername && $password==$dbpassword)
{
echo "Login successul .<a href='memeberarea.php'>Click to enter member area</a>";
$_SESSION['username'] = $dbusername;
}
else
echo "incorrect password ";
}
else
die ("That user name dosent exist");
}
else
die ("Please enter a username and password");
?>
Even if i put right or wrong password or don't put password or i write the name of the data base wrong . all of this wrongs i have the same error message
Typo: localhsost for one thing. Plus, you may not be able to use mysql_ functions, since they are deprecated and may not be available for you to use.
Plus, your POST arrays may be failing, so make sure your form is a POST method and that your elements bear the name attribute.
I.e.:
<input type="text" name="username">
etc.
if i write wrong name database i don't have any error . why ?"
Because, you're just using or die("Couldent connet to database ") instead of getting the real error mysql_error()
mysql_connect() => http://php.net/manual/en/function.mysql-connect.php
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
For password storage, use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
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.
Plus, instead of if ($username && $password) you should be using a conditional !empty() for your inputs.
It is also best to use proper and consistent bracing throughout your code.
else{
echo "incorrect password ";
}
etc.
Not doing so, could have adverse effects.
Storing a password hash
Using PDO with prepared statements and password_hash():
Pulled from ircmaxell's answer: https://stackoverflow.com/a/29778421/
Just use a library. Seriously. They exist for a reason.
PHP 5.5+: use password_hash()
PHP 5.3.7+: use password-compat (a compatibility pack for above
All others: use phpass
Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.
$dbh = new PDO(...);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);
And on login:
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
if (password_verify($_POST['password'], $users[0]->password) {
// valid login
} else {
// invalid password
}
} else {
// invalid username
}
You may print some information for yourself, so you could see, what's wrong. Change the following line:
echo "incorrect password ";
to something like this:
echo "incorrect password, u:[$username/$dbusername] p:[$password/$dbpassword]";
If you will see that detailed message, you will know, what's wrong.
EDIT: of course, don't left pwd printing in your final code :)

Having an issue confirming data using mysql with my database

Okay I have been using mysql for use with my website however it has not been going well with some of the syntax. I've read up on it but I fell like I'm still doing it wrong... In the picture below, I have defined database variables and then tried to log into my database containing the columns of "ID" "Username" and "Password". I then define the username and password input, from my form, in the php and asked the database to compare... am I missing something? I feel like it's not comparing the data from the form with the data in the database. It works even if I type the password wrong..
//Name of File: LoginCheck.php <--Called with the Login.php (which has a form on it)
//posts information to LoginCheck.php
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'blah');
define('DB_PASS', 'blah');
define('DB_NAME', 'Profiles');
$con = mysql_connect(DB_HOST, DB_USER, DB_PASS);
if(!$con){
die('Could not connect. ' . '<br/>' . 'Error: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $con);
if(!$db_selected){
die('Could not select database: ' . DB_NAME . '<br/>' . 'Error: ' . mysql_error());
}
//defines login variables from the form.
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$login = mysql_query("SELECT * FROM Users WHERE Username = '$username' AND Password = '$password'", $con);
if(!$login){
echo 'Error: ' . mysql_error();
echo "Didn't log in. Not matching database intel.";
}else{
echo "Logged in matching database intel.";
}
mysql_close($con);
?>
mysql_query() just returns a resource. You can then use that resource to get that data or more information about the query.
You can use mysql_num_rows() to see if your query was successful:
if(!mysql_num_rows($login)){
FYI, you should not be storing passwords in plain text. That is a huge security no-no.
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
It should be:
$login = mysql_query("SELECT * FROM Users WHERE Username = '$username' AND Password = '$password'", $con);
if(!$login){
echo 'Error: ' . mysql_error();
} elseif (mysql_num_rows($login) == 0) {
echo "Didn't log in. Not matching database intel.";
}else{
echo "Logged in matching database intel.";
}
Not finding a match is not the same as an error.

PHP login check flow

Im having trouble with a php login script (below). I want to redirect to nouser.php if someone enters a username that does not exist and to wrongpass.php if the wrong password (but a valid username) is entered. The below code almost works. If I comment out the entire wrong password section then the nouser section works as expected displaying the nouser page , but if I leave the wrong password section in I get the wrongpass.php page for both nouser and wrong password situations. If I put a valid user in but with wrong password then I get wrong password (correct behavior).
Simply put , how can i make sure that I get redirect to nouser.php if there is nouser of this name and not the wrongpass.php page..
<?php
$username = $_POST['username'];
$password = $_POST['password'];
//connect to the database here
require_once 'includes/login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
$username = mysql_real_escape_string($username);
$query = "SELECT password, salt
FROM users
WHERE username = '$username';";
$result = mysql_query($query);
//wrong user section
if(mysql_num_rows($result) < 1) //no such user exists
{
header('Location: nouser.php');
}
//wrong password section
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
if($hash != $userData['password']) //incorrect password
{
header('Location: wrongpass.php');
}
//login successful
?>
I think you should add die() to stop the script
if(mysql_num_rows($result) < 1) {
header('location:nouser.php');
die();
}
Has not yet test the code.

Categories