This is my code
$username = $_POST['user'];
$password = $_POST['pass'];
if (isset($_POST['user'])); {
$db = mysqli_connect('localhost', 'root', '', 'db');
if($query = mysqli_query($db, "SELECT `pass` FROM `accounts` WHERE `user` = '$username'")){
while($row = mysqli_fetch_assoc($query)){
$row['pass'] = $setpassword;
}
mysqli_free_result($query);
}
}
What it currently does is from a form, retrive a username and password that the user has entered, take that username and find the row with that username and get the password from that row and set it as the variable $setpassword. Below is the code to check if the password matches the given username on the database.
if ($password=='') {
$verify = 0;
}
if ($password!='') {
if ($password!=$setpassword) {
$verify = 1;
}
if ($password==$setpassword) {
$verify = 2;
}
}
If verify is...
0 - The Login Form Will appear as nothing has been entered.
1 - Incorrect Password will be displayed along with the login form.
2 - Correct Password will be displayed and the username will be assigned to a session variable.
I'm having a problem where a user can enter a username that doesnt exist and any password wether its in the database or not and it will be verified.
What can I do to check if the username doesn't exist on the database?
When you are accepting the user's registration query the database to see if it already exists.
$result = mysqli_query("SELECT * FROM accounts where `user` = $username");
if(mysql_num_rows($result) >0) // if there are any rows returned then the username exists
{
//User Name already exists
}
else
{
//User name doesn't exist, add user
}
I'm not sure this is where you are doing that. But to eliminate duplicates you can do it that way. Also, you can define the column user as unique. That way the SQL will not allow duplicate values.
Also this line:
$row['pass'] = $setpassword; //setting $row['pass'] to $setpasswords value.
This is reversed. You should be doing it the other way around.
$setpassword = $row['pass']; //setting setpassword to $row['pass'] value.
Let me know if I need to clarify anything.
Try this:
$username = isset($_POST['user'])?$_POST['user']:''; // check if isset to avoid notice
$password = isset($_POST['pass'])?$_POST['pass']:'';
$verify = 0;
if (!empty($username)) {
$db = mysqli_connect('localhost', 'root', '', 'db');
if($query = mysqli_query($db, "SELECT `pass` FROM `accounts` WHERE `user` = '$username'")) {
while($row = mysqli_fetch_assoc($query)){
$setpassword = $row['pass'];
break; // exit the loop once you found the password
}
mysqli_free_result($query);
}
if (isset($setpassword)) {
$verify = 1;
if ($password == $setpassword) {
$verify = 2;
}
}
if (isset($_POST['user'])); {
there is an extra semicolon in this line, making whole code not working
to do your verification, all you need is to retrieve the password and compare it with entred one:
$row = mysqli_fetch_assoc($query));
if ($row AND $row['pass'] == $password)
$verify = 1;
}
note that $row could be ampty, so, you have to check it first
however, you can do both comparisons in the query, like this
"SELECT * FROM accounts where `user` = $username" AND `pass` = '$password';
However, your code suffers from 2 common problems.
It is better to save a hash instead of the plain password.
You should sanitize your data before adding it in the query
at least this way:
$username = mysqli_real_escape_string($db,$_POST['user']);
Related
If i enter wrong password it shows 'Wrong username or Password' but if enter wrong username and correct password it shows nothing. Why ? what should i change in the code?
<?php
$name = $_POST['username'];
$password=$_POST['pwd'];
$dbc = mysql_connect('localhost', 'username', 'password') or die();
mysql_select_db("dbname") or die();
$result = mysql_query("SELECT * FROM table WHERE uname='$name'") or die(mysql_error());
while($row = mysql_fetch_array($result))
{
if($row['uname']==$name && $row['pword']==$password)
{
echo 'Successfully logged in <br />';
break;
}
else
{
echo 'Wrong username or password';
}
}
mysql_close($dbc);
?>
Because if you enter the wrong username the query returns nothing.
Then you don't get into the while loop.
You could change the query :
$result = mysql_query("SELECT * FROM table WHERE uname='".addslashes($name)."' and pword='".addslashes($password)."'");
Then use mysql_fetch_row() only once (remove your while loop).
EDIT
<?php
function hash_password($password){
$myVerySecretSalt = "pREkeSw2"; //don't use this string, create your own random one!
return md5($myVerySecretSalt.$password.$myVerySecretSalt);
}
$name = $_POST['username'];
$password = hash_password($_POST['pwd']);
$dbc = mysqli_connect('localhost', 'username', 'password') or die();
mysqli_select_db("dbname") or die();
$mysql_result = mysqli_query("SELECT * FROM table WHERE uname='".addslashes($name)."' and pword='".$password."'");
$result = mysqli_fetch_row($mysql_result);
mysqli_close($dbc);
if(!$result){
echo "Wrong username or password.";
}else{
var_dump($result);
echo "Successfully logged in.";
}
?>
EDITED for usage of MySQLi as mysql is deprecated since PHP 5.5
EDITED as for plaintext passwords.
It's never a very good thing to store passwords in plaintext in the database as they can be stolen in case of sql injection.
A way to protect your users password is to hash them, below is a basic implementation :
First create a function to hash a password :
function hash_password($password){
$myVerySecretSalt = "pREkeSw2"; //don't use this string, create your own random one!
return md5($myVerySecretSalt.$password.$myVerySecretSalt);
}
Then replace your third line $password = $_POST['pwd']; with this one : $password = hash_password($_POST['pwd']);
Here you go! (Just remember to use that same function on the password when you create the user account)
This should work correctly:
<?php
$name = $_POST['username'];
$password=$_POST['pwd'];
$dbc = mysql_connect('localhost', 'username', 'password') or die();
mysql_select_db("dbname") or die();
$result = mysql_query("SELECT * FROM table WHERE uname='$name'") or die(mysql_error());
$row= mysql_fetch_array($result)
if($row && $row['uname']==$name && $row['pword']==$password)
{
echo 'Successfully logged in <br />';
break;
}
else
{
echo 'Wrong username or password';
}
mysql_close($dbc);
?>
your previous code didn't show anything becasue row = mysql_fetch_array($result) were not finding any record, and so returning immediately false (and exied the while)
Seems like you enter a username that does not exist in that table.
Remove your while loop. Just say:
$result = mysql_fetch_assoc(mysql_query("SELECT * FROM table WHERE uname = '".mysql_real_escape_string($name)."' AND pword = '".mysql_real_escape_string($password)."'"));
if ($result) {
// Successfully logged in
} else {
// Login failed
}
Keep in mind that the mysql_real_escape_string is very important when accepting user input to avoid SQL injection.
Since you are authenticating a user, record must be unique.
Thus, you shouldn't be looping through anything:
Get rid of the loop and change your conditions
$row = mysql_fetch_array($result);
if($row['uname']==$name && $result){
if($row['pword']==$password){
echo 'Successfully logged in <br />';
}else{
echo 'Wrong Password';
}
}else{
echo 'No record found';
}
mysql_close($dbc);
I refactored your code for this one. I recommend use mysql_fecth_row instead mysql_fetch_array beacause you need just one row.
<?php
// get, validate and clean your input variables
$name = isset($_POST['username']) ? addslashes($_POST['username']) : '';
$password =isset($_POST['pwd']) ? addslashes($_POST['pwd']) : '';
// make your data base connection
$dbc = mysql_connect('localhost', 'root', '') or die();
mysql_select_db("test_mysql") or die();
// building the sql query and getting the result (remember filter by username and password)
$result = mysql_query("SELECT * FROM tb_usuario WHERE uname = '$name' AND pword = '$password'") or die(mysql_error());
// using mysql_fetch_row (remember that just one user must match in the data base if not something is wrong in register ...)
$row = mysql_fetch_row($result);
// remember 0 => id, 1 => uname, 2 => pword
if (is_array($row)) {
echo "Welcome {$row[1]}";
} else {
echo 'Wrong username or password';
}
// close your connection
mysql_close($dbc);
For some reason inputs in my login page don't seem to be getting processes correctly. Correct user inputs are getting returned as invalid (wrong password) having had a look through, I can't see anything particularly obvious. But I can only assume the username or password isn't getting passed for some reason. Would someone more experienced be able to take a look and suggest how I can put it right. Thanks guys. P.S My form is OK, so not included.
function logcon($user, $password )
{
$user = mysqli_real_escape_string($this->conn, $user);
$esc_password = mysqli_real_escape_string($this->conn,$password);
$sql = "SELECT * from USERS WHERE username ='{$user}' AND password='{$password}'";
$result = mysqli_query($this->conn, $sql);
$row = mysqli_fetch_array($result);
return $row;
}
Login page.
if(isset($_POST['submit'])){
$user=$_POST['user'];
$password=$_POST['password'];
//To ensure that none of the fields are blank when submitting the form if
if(isset($_POST['user']) && isset($_POST['password']))
{
$user = stripslashes($user);
$password = stripslashes($password);
$db1=new dbmember();
$db1->openDB();
$row=$db1->logcon($user, $password);
if($row[0]==1)
{
session_start();
$_SESSION['user'] = $user;
$_SESSION['password'] = $password;
$_SESSION['loggedin'] = "true";
header("location:index.php");
}
else
{
print ('<div id="error">Acess denied, wrong username or password?</div>');
}
}
else
{
print ('<div id="error">Enter something!</div>');
}
}
It appears you are using the wrong variable name in your query. I would also suggest you look into doing some sort of hashing and salting of your passwords instead of saving them as plain text.
$sql = "SELECT * from USERS WHERE username ='{$user}' AND password='{$password}'";
should be
$sql = "SELECT * from USERS WHERE username ='{$user}' AND password='{$esc_password}'";
And your conditional check seems off, you are checking to see if the first field in the results is = 1 instead of seeing if there is a return.
if($row[0]==1)
Should probably be
if($row)
My code works but it only works for the first row. When I insert another row in MySQL and try and log-in with the different username and password it returns my error. What's wrong?
<?php
include_once('db.php');
$username = $_POST['username'];
$password = sha1($_POST['password']);
if(!empty($username) && !empty($password)) {
$loginSQL = "SELECT * FROM `users` WHERE `username` = '$username' AND `password` = '$password'";
if($db->query($loginSQL)->fetchColumn() == 1) {
$fetchUsers = $db->query($loginSQL)->fetch(PDO::FETCH_ASSOC);
$userID = $fetchUsers['uid'];
$_SESSION['uid'] = $userID;
echo '<br /><br />You have successfully logged in. Click here to proceed.';
}
else {
echo '<br /><br />You have entered invalid log-in information.';
}
}
else {
echo '<br /><br />You have entered invalid log-in information.';
}
?>
Two biggest problems are double fetch and lack of prepared statements.
<?php
include_once('db.php');
if(!empty($_POST['username'])) {
$username = $_POST['username'];
$password = sha1($_POST['password']);
$sql = "SELECT uid FROM `users` WHERE `username` = ? AND `password` = ?";
$stm = $db->prepare($sql);
$stm->execute(array($username,$password);
if($row = $stm->fetch()) {
$_SESSION['uid'] = $row['uid'];
}
}
There are a few problems here.
fetchColumn() returns the first column of the first row, which might or might not be 1 depending on how the DB table is set up.
fetch() returns the current row the PDOStatement row pointer is on. If you don't send it to the next row, it won't move.
You are sending the same error for two different reason, helping to lead to confusion.
What would really help you is if you would restructure your code like #Your Common Sense shows and look at it then. It will help yourself better see the problem.
I'm new to PHP and programming in general, but am working on doing a login. I've got the signup page completed, and my database populates the records fine. However, when this code gets output it says I have 0 rows from the mysql_num_rows($result);... when, it should be coming back successfully showing 1 row when I input the correct username/password. Whether I put in a successful user/pass combo or not, it outputs the same.
I appreciate any help you can provide, code is listed below:
$SQL = "SELECT * FROM account WHERE username = $username AND password = md5($password)";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
echo $result;
echo $num_rows;
// CLOSE CONNECTION
mysql_close($db_handle);
// COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS PAGE
if ($result) {
if ($num_rows > 0) {
session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");
}
else {
$error_message = "Login failed. Please try again.";
echo $num_rows;
EDIT: Complete rewrite
Try this:
<?php
$host = "host";
$user = "user";
$password = "password";
$database = "database";
$username = 'jack'; /* Insert $_Post [''] here with username variable you pass. You could sanitize and validate with for example filter_var (), clean (), etc */
$password_user = 'password from jack'; // same here.
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE{
$query = "SELECT * FROM account WHERE username ='$username' AND password = md5('$password_user')";
$result = mysqli_query($link, $query);
$num_rows = mysqli_num_rows($result);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
// COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS PAGE
if ($row) {
session_start();
$_SESSION['login'] = "1"; // pleae not that 1 is converted into a string value
$_SESSION['username'] = $username; // added username, just to test.
header ("Location: page1.php");
}
else {
$error_message = "Login failed. Please try again.";
echo $error_message;
}
// CLOSE CONNECTION
mysqli_close($link);
}
?>
Sample data:
CREATE TABLE account (
id INT auto_increment primary key,
username VARCHAR(30),
password VARCHAR(50)
);
INSERT INTO account(username, password)
VALUES
("bob", md5('password from bob')),
("jack", md5('password from jack')),
('joe', md5('password from joe'));
SQL FIDDLE DEMO
Sample page1
<?php
session_start();
$login = $_SESSION['login'];
$username = $_SESSION['username'];
echo '<h1>It WORKS, <i>'.$username.'</i>!!!</h1>';
?>
Important to note is that I have used the MYSQLI library instead of the MYSQL library. If you have more than one column in you table you should select your output per column. For example, $result['id'].
I found that you didn't escape variable in and out in you SQL statement. I have to note that I didn't debug the part below COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS. I think you can manage that on your own.
W.R.T. the santization and validation you have to do some more work. I don't know how you data is past via the user login in form. Let say you will use POST. In that case you can start at the top of you page with first retrieving all the posted variable using $_POST. Then filter them to make sure you code in is not open for SQL injection. E.g. $username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
i have this code, and i'm trying to create a session in order to get user's gallery id..
The problem is, if i use $_SESSION['username'] it works, but like this not... can you please check what's wrong with this?
Thanks!
mysql_connect($host, $user, $pass);
mysql_select_db($database);
$username = mysql_real_escape_string($_POST['username']);
$password = md5($_POST['password']);
$result = mysql_query("SELECT * FROM $table WHERE username = '$username' AND password = '$password'
");
while ($rows = mysql_fetch_array($result)) {
if(mysql_num_rows($result))
{
$rows['gal_id']=$gal_id;
session_start();
$_SESSION['gal_id'] = htmlspecialchars($gal_id);
}
else
{
// Invalid username/password
echo '<p><strong>Error:</strong> Invalid username or password.</p>';
}
change this:
$rows['gal_id']=$gal_id;
to
$gal_id=$rows['gal_id'];
EDIT: i dont think it need a furhter explanation
$rows['gal_id']=$gal_id; You cannot set the value of a database row by doing this. Plus it is never further referenced.
session_start(); This should be at the top of your page in most instances.
$_SESSION['gal_id'] = htmlspecialchars($gal_id); $gal_id is never set in your code to anything, it doesn't exist.