Reputation: 11
I created the code below for people to login on a site but the results keep saying:
wrong username or password
and I don't know what's wrong. The database has a table "clients" with columns names "usernames" and "passwords".
<?php
$host = ""; // Host name
$username = ""; // Mysql username
$password = ""; // Mysql password
$db_name = ""; // Database name
$tbl_name = "clients"; // Table name
$con = mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
$username = $_POST['myusername'];
$password = $_POST['mypassword'];
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql = "SELECT `username` FROM `clients` WHERE `username`='$myusername' and `password`='$mypassword'";
$result = mysql_query($sql) or die(mysql_error());
// Mysql_num_row is counting table row
if ($result) {
$count = mysql_num_rows($result);
}
else {
$count = 0;
}
// If result matched $myusername and $mypassword, table row must be 1 row
if ($count == 1) {
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
header("location:source/login_success.php");
}
else {
echo "Wrong Username or Password";
}
?>
Upvotes: 1
Views: 721
Reputation: 798
It would be a good idea not to register the password in the session. A better practice is to set the session with the id of the user (say that in your mysql table, you have: id, username, password, etc.). It is a better and more secure way to do. And then, on the pages that you require to be logged in, you just do:
<?php
session_start();
if(!isset($_SESSION['id']) {
..... display error message and redirect user to login page....
}
?>
Upvotes: 0
Reputation: 28936
The problem is here:
$username = $_POST['myusername'];
$password = $_POST['mypassword'];
$myusername = stripslashes($myusername); // Using uninitialized '$myusername'
$mypassword = stripslashes($mypassword); // Using uninitialized '$mypassword'
$myusername
and $mypassword
are unitialized when passed to stripslashes()
, so the result will always be empty.
To correct this problem, adjust the variable names passed to stripslashes()
:
$myusername = stripslashes($username);
$mypassword = stripslashes($password);
Upvotes: 5
Reputation: 1
$username = $_POST['myusername'];
$password = $_POST['mypassword'];
TRY THIS
$myusername = $_POST['myusername'];
$mypassword = $_POST['mypassword'];
Upvotes: -1
Reputation: 40096
Change this:
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
to this:
$myusername = stripslashes($username);
$mypassword = stripslashes($password);
Upvotes: 1