I cannot get my login form to connect interact properly with mySQL database
This answer is for hashing, password_hash(), and password_verify(). For both mysqli and pdo. The link at the bottom has further links and some language about salts and the like.
It is crucial to not use user-supplied data directly with selects and inserts. Rather, bind parameters and call prepared statements to Avoid sql injection attacks. Passwords should never be saved in the clear (cleartext) in databases. Rather, they should be sent through one-way hashes.
Also note. This is showing registration hashing and login verify. It is not full blown functionality I am trying to hock on codecanyon for ten bucks ... such that it shows a re-registration of an email address (the login) already exists, does updates, mind you. In that case the insert will simply fail due to the unique key set in place in the db. I leave that to you, the reader, to do the lookup, and say 'email already registered.'
Schema
CREATE TABLE `user_accounts2` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(100) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
unique key(email) -- that better be the case
) ENGINE=InnoDB;
After running through register.php and saving a user, the data might look like this:
select * from user_accounts2;
+----+-----------+--------------------------------------------------------------+
| id | email | password |
+----+-----------+--------------------------------------------------------------+
| 1 | d@d.com | $2y$10$U6.WR.tiOIYNGDWddfT7kevJU8uiz8KAkdxXpda9e1xuplhC/eTJS |
+----+-----------+--------------------------------------------------------------+
mysqli section first
register.php
<?php
mysqli_report(MYSQLI_REPORT_ALL);
error_reporting(E_ALL); // report all PHP errors
ini_set("display_errors", 1); // display them
session_start();
if(isset($_SESSION['userid'])!="") {
// you are already logged in as session has been set
header("Location: safe.php"); // note that this re-direct will at the top of that page
// ... and there to verify the session state so no tricks can be performed
// no tricks and gimmicks
}
if(isset($_POST['register'])) {
$email = $_POST['email'];
$ctPassword = $_POST['password']; // cleartext password from user
$hp=password_hash($ctPassword,PASSWORD_DEFAULT); // hashed password using cleartext one
// pretend the following is locked in a vault and loaded but hard coded here
$host="yourhostname";
$dbname="dbname";
$user="dbuser";
$pwd="password";
$port=3306; // comes along for the ride so I don't need to look up param order below
// end pretend
try {
$mysqli= new mysqli($host, $user, $pwd, $dbname,$port);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
//echo "I am connected and feel happy.<br/>";
$query = "INSERT INTO user_accounts2(email,password) VALUES (?,?)";
$stmt = $mysqli->prepare($query);
// note the 2 s's below, s is for string
$stmt->bind_param("ss", $email,$hp); // never ever use non-sanitized user supplied data. Bind it
$stmt->execute();
// password is saved as hashed, will be verified on login page with password_verify()
$iLastInsertId=$mysqli->insert_id; // do something special with this (or not)
// redirect to some login page (for now you just sit here)
$stmt->close();
$mysqli->close();
} catch (mysqli_sql_exception $e) {
throw $e;
}
}
?>
<html>
<head>
<title>Register new user</title>
</head>
<body>
<div id="reg-form">
<form method="post">
<table>
<tr>
<td><input type="email" name="email" placeholder="Email" required /></td>
</tr>
<tr>
<td><input type="password" name="password" placeholder="Password" required /></td>
</tr>
<tr>
<td><button type="submit" name="register">Register</button></td>
</tr>
<tr>
<td><a href="index.php">Normal Login In Here</a></td>
</tr>
</table>
</form>
</div>
</body>
</html>
login.php
<?php
mysqli_report(MYSQLI_REPORT_ALL);
error_reporting(E_ALL); // report all PHP errors
ini_set("display_errors", 1); // display them
session_start();
if(isset($_SESSION['userid'])!="") {
// you are already logged in as session has been set
header("Location: safe.php"); // note that this re-direct will at the top of that page
// ... and there to verify the session state so no tricks can be performed
// no tricks and gimmicks
}
if(isset($_POST['login'])) {
$email = $_POST['email'];
$ctPassword = $_POST['password']; // cleartext password from user
// pretend the following is locked in a vault and loaded but hard coded here
$host="yourhostname";
$dbname="dbname";
$user="dbuser";
$pwd="password";
$port=3306; // comes along for the ride so I don't need to look up param order below
// end pretend
try {
$mysqli= new mysqli($host, $user, $pwd, $dbname,$port);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
//echo "I am connected and feel happy.<br/>";
$query = "select id,email,password from user_accounts2 where email=?";
$stmt = $mysqli->prepare($query);
// note the "s" below, s is for string
$stmt->bind_param("s", $email); // never ever use non-sanitized user supplied data. Bind it
$stmt->execute();
$result = $stmt->get_result();
if ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$dbHashedPassword=$row['password'];
if (password_verify($ctPassword,$dbHashedPassword)) {
echo "right, userid=";
$_SESSION['userid']=$row['id'];
echo $_SESSION['userid'];
// redirect to safe.php (note safeguards verbiage at top of this file about it)
}
else {
echo "wrong";
// could be overkill here, but in logout.php
// clear the $_SESSION['userid']
}
}
else {
echo 'no such record';
}
// remember, there is no iterating through rows, since there is 1 or 0 (email has a unique key)
// also, hashes are one-way functions in the db. Once you hash and do the insert
// there is pretty much no coming back to cleartext from the db with it. you just VERIFY it
$stmt->close();
$mysqli->close();
} catch (mysqli_sql_exception $e) {
throw $e;
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<div id="reg-form">
<form method="post">
<table>
<tr>
<td><input type="email" name="email" placeholder="Email" required /></td>
</tr>
<tr>
<td><input type="password" name="password" placeholder="Password" required /></td>
</tr>
<tr>
<td><button type="submit" name="login">Login</button></td>
</tr>
</table>
</form>
</div>
</body>
</html>
pdo section below
When I have time, probably tomorrow, but for now I point you to this Answer of mine.
PHP & MySQL login authentication database check not working properly?
Change
strtoupper($usrUsr) == strtoupper($row["USER"])
To
strtoupper($usrUser) == strtoupper($row["USER"])
Fetch single user from the database by using the username since they are unique for each user.
$sql = "SELECT ID, USER, PASSWORD FROM usrdatabase WHERE USER = '" . mysqli_real_escape_string($_POST['usr']) . "' AND PASSWORD = '" . mysqli_real_escape_string($_POST['pass']) . "'";
Log In Form not interacting with MySQL
Check what you have in your mysql_connect.php that you are using the correct username and password to connect to your mysql database. On your development localhost you probably connect with the root user, but you can't use that on your webserver. In the cPanel or whatever you have to configure your web site, add a user (with select/insert/delete access) and allow it to connect to your database. Use that user's credentials in your mysql_connect.php.
Log in form using php and mysql isnt working?
I can't speak for the rest of the code: but you are checking for
if (isset($_POST['rpemail'])) {
but the email that in your posted form is
<input name="email" type="text" id="email" />
These will need to be the same
if (isset($_POST['email'])) {
also you are concatenating $pass, but it isn't defined (unless it is in the required file):
$pass .= $tmp;
should simply be
$pass = $tmp;
PHP Login form does not work, what can i do to fix it?
You're not setting the value of $username correctly.
Change:
$password = trim($_POST['username']);
To:
$username = trim($_POST['username']);
$hashed_password has to have a value since it's needed in password_verify(). Used mysqli's bind_result and fetch methods to get the value needed.
After:
if(mysqli_stmt_num_rows($stmt) == 1){
Add:
$hashed_password = "";
$username2 = "";
mysqli_stmt_bind_result($stmt, $username2, $hashed_password);
mysqli_stmt_fetch($stmt);
Added exit(); after header(..) redirect so no other codes will be executed after the redirect call.
Updated Code:
<?php
require_once 'config.php';
$username = $password = '';
$username_err = $password_err = '';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty(trim($_POST["username"]))){
$username_err = 'Please enter an username!';
}
else {
$username = trim($_POST['username']);
}
if (empty(trim($_POST["password"]))){
$pasword_err = "Please enter a password!";
}
else {
$password = trim($_POST['password']);
}
if (empty($username_err) && empty($password_err)) {
$sql = "SELECT username,password FROM members WHERE username = ?";
if ($stmt = mysqli_prepare($link, $sql)) {
mysqli_stmt_bind_param($stmt, "s", $param_username);
$param_username = $username;
if (mysqli_stmt_execute($stmt)){
mysqli_stmt_store_result($stmt);
if (mysqli_stmt_num_rows($stmt) == 1){
$hashed_password = "";
$username2 = "";
mysqli_stmt_bind_result($stmt, $username2, $hashed_password);
mysqli_stmt_fetch($stmt);
if (password_verify($password, $hashed_password)){
$_SESSION['username'] = $username;
mysqli_stmt_close($stmt);
mysqli_close($link);
header("location: welcome.php"); exit();
}
else{
$username_err = 'Username/password is wrong!';
}
}
else {
echo "Oops! Something went wrong. Please try again later.";
}
}
mysqli_stmt_close($stmt);
}
mysqli_close($link);
}
}
?>
PHP, MySQL Login Issue After Adding More Table Columns/Inputs
MD5 processes an arbitrary-length message into a fixed-length output of 128 bits, typically represented as a sequence of 32 hexadecimal digits. md5($password)
Returns the hash as a 32-character hexadecimal number.
You used password
length varchar(15)
like bellow:
`password` varchar(15) NOT NULL
it should be minimum length 32 or more then like bellow
`password` varchar(32) NOT NULL
Creating login page with php and mysql
Try using mysqli
as mysql
is depreciated.
You don't need a loop here. just check with mysqli_num_rows
like
if(mysqli_num_rows($sql) > 0){
echo "Login Successfull" ;
}else {
echo "<br> Invalid Email or Password";
}
Cannot log in with created user in mysql
You probably have this perpetual MySQL problem where one of the default users in the user table is '' @ localhost
, which winds up denying all localhost
users later in the table. What I would do is mysqldump
the mysql
database and look for this entry in the User
table; if found, delete it and flush privileges.
For more details see https://dev.mysql.com/doc/refman/5.5/en/connection-access.html.
It is a common misconception to think that, for a given user name, all rows that explicitly name that user are used first when the server attempts to find a match for the connection. This is not true. The preceding example illustrates this, where a connection from h1.example.net by jeffrey is first matched not by the row containing 'jeffrey' as the User column value, but by the row with no user name. As a result, jeffrey is authenticated as an anonymous user, even though he specified a user name when connecting.
I cannot seem to connect my PHP page to my SQL test server and database
Have you try to edit your php :
isset($_POST['Submit']
and change it to :
isset($_POST['submit']
variable $_POST is case-sensitive so you should use the exact same name that you assign in your html code.
CMIIW
Related Topics
Pdo With "Where... In" Queries
Insert - Number of Bind Variables Doesn't Match Number of Fields in Prepared Statement
How to Best Store User Information and User Login and Password
How to Use Arrays in Curl Post Requests
Upload Multiple Files With PHP and Jquery
Best Way to Automatically Remove Comments from PHP Code
How to Use Sha1 Encryption Instead of Bcrypt in Laravel 4
Json_Decode Returns Json_Error_Syntax But Online Formatter Says the Json Is Ok
In PHP, What Does "≪≪≪" Represent
How to Re-Index the Values of an Array in PHP
Return Index of Highest Value in an Array
With "Magic Quotes" Disabled, Why Does PHP/Wordpress Continue to Auto-Escape My Post Data