I'm trying to lock out a certain page to one user, with a username and a password. I tried a couple things, but what I think I need is a sort of login function. I have made logins before, so I used code of mine that I used before. For some reason however, it gives me an error that I coded in to know that the password is incorrect, even though it isn't. To make it a bit easier to see which specific error message is given, I've put in a 1 and a 2 behind the error, i get error number 1.
Below is my php code and below that is my html form I use.
$username = $password = "";
$username_err = $password_err = $login_err = "";
function pr($data, $kill_script = false)
{
echo '<pre>'.print_r($data,1).'</pre>';
if($kill_script) exit;
}
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = "Please enter username.";
}
else{
$username = trim($_POST["username"]);
}
// Check if password is empty
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
}
else{
$password = trim($_POST["password"]);
}
// Validate Credentials
if(empty($username_err) && empty($password_err)){
//prepare a select statement
$sql = "SELECT username, password FROM user_confirm WHERE username = :username";
if($stmt = $conn->prepare($sql)){
// bind variables to the prepared statement as parameters
$stmt->bindParam(":username", $param_username, PDO::PARAM_STR);
//set parameters
$param_username = trim($_POST["username"]);
if($stmt->execute()){
// check if username exits, if yes then verify password
if($stmt->rowCount() == 1){
if($row = $stmt->fetch()){
$username = $row["username"];
$hashed_password = $row["password"];
if(password_verify($password, $hashed_password)){
// password is correct, so start new session
session_start();
//store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["username"] = $username;
//redirect user to welcome page
header("location: werk_edit.php");
}
else{
//invalid password, display error message
$login_err = "Invalid username or password. 1";
}
}
}
else{
//username doesn't exist, display error message
$login_err = "Invalid username or password. 2";
}
}
else{
echo "Something went wrong, please try again later.";
}
//close statement
unset($stmt);
}
}
//close connection
unset($conn);
}
HTML Form:
<?php
if(!empty($login_err)){
echo '<div class="alert alert-danger">' . $login_err . '</div>';
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<label>Username</label>
<input type="text" name="username" class="form-control <?php echo (!empty($username_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $username; ?>">
<span class="invalid-feedback"><?php echo $username_err; ?></span>
<label>Password</label>
<input type="password" name="password" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>">
<span class="invalid-feedback"><?php echo $password_err; ?></span>
<input type="submit" name="login" class="btn btn-primary" value="Login">
</form>
Related
I am using Mac OS, mamp, phpmyadmin to create a simple login form. I have created my database in php myadmin and the first user. I am certain the username and password are correct (as per my database) but I receive the error that the password is incorrect.
I was loosely following this tutorial https://www.tutorialrepublic.com/php-tutorial/php-mysql-login-system.php
I believe this may be causing the error but i'm unsure.
$hashed_password = $row["password"];
if(password_verify($password, $hashed_password)){
<?php
// Initialize the session
session_start();
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: welcome.php");
exit;
}
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = "Please enter username.";
} else{
$username = trim($_POST["username"]);
}
// Check if password is empty
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
} else{
$password = trim($_POST["password"]);
}
// Validate credentials
if(empty($username_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT id, username, password FROM users WHERE username = :username";
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":username", $param_username, PDO::PARAM_STR);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
// Check if username exists, if yes then verify password
if($stmt->rowCount() == 1){
if($row = $stmt->fetch()){
$id = $row["id"];
$username = $row["username"];
$hashed_password = $row["password"];
if(password_verify($password, $hashed_password)){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
// Redirect user to welcome page
header("location: welcome.php");
} else{
// Display an error message if password is not valid
$password_err = "The password you entered was not valid.";
}
}
} else{
// Display an error message if username doesn't exist
$username_err = "No account found with that username.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
unset($stmt);
}
// Close connection
unset($pdo);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Login</h2>
<p>Please fill in your credentials to login.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Login">
</div>
<p>Don't have an account? Sign up now.</p>
</form>
</div>
</body>
</html>
I expect to be taken to my welcome screen.
To fix I replaced
$hashed_password = $row["password"];
if(password_verify($password, $hashed_password)){
with
$hashed_password = password_hash( $_POST["password"], PASSWORD_DEFAULT);
if(password_verify($_POST["password"], $hashed_password)){
This hash passwords before storing them in db then verifies the plan text against the hashed password
Verify method is expecting the hashed password. Your $row["password"]contains hashed password (if you use password_hash() function in user registration) while the password received with $_POST is a plain text password.
Use the following:
if (password_verify($_POST["password"], $row["password"])) {
// User authorized
} else {
// User non authorized
}
I am implementing login system from
https://www.tutorialrepublic.com/php-tutorial/php-mysql-login-system.php
I successfully connected the config.php to the database mathbglogin. When I register everything goes smoothly but when I try to login I receive an error that the password is incorrect. The database structure is as following localhost > users > mathbglogin.
I tried to isolate the problem. My guess is that the password is not compared with hash in the right way(i'm new to php).
Login if
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
// Redirect user to welcome page
header("location: welcome.php");
} else{
// Display an error message if password is not valid
$password_err = "The password you entered was not valid.";
}
}
I have attached the other scripts if this can help. My second guess is that the passwords are not encrypted right for which the register.php can be blamed.
Login form image
Database table preview
Full login.php
<?php
// Initialize the session
session_start();
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: welcome.php");
exit;
}
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = "Please enter username.";
} else{
$username = trim($_POST["username"]);
}
// Check if password is empty
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
} else{
$password = trim($_POST["password"]);
}
// Validate credentials
if(empty($username_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT id, username, password FROM mathbglogin WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = $username;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Store result
mysqli_stmt_store_result($stmt);
// Check if username exists, if yes then verify password
if(mysqli_stmt_num_rows($stmt) == 1){
// Bind result variables
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
// Redirect user to welcome page
header("location: welcome.php");
} else{
// Display an error message if password is not valid
$password_err = "The password you entered was not valid.";
}
}
} else{
// Display an error message if username doesn't exist
$username_err = "No account found with that username.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Login</h2>
<p>Please fill in your credentials to login.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Login">
</div>
<p>Don't have an account? Sign up now.</p>
</form>
</div>
</body>
</html>
Full register.php
<?php
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT id FROM mathbglogin WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Validate password
if(empty(trim($_POST["password"]))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST["password"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = "Please confirm password.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if(empty($password_err) && ($password != $confirm_password)){
$confirm_password_err = "Password did not match.";
}
}
// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
// Prepare an insert statement
$sql = "INSERT INTO mathbglogin (username, password) VALUES (?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);
// Set parameters
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location: login.php");
} else{
echo "Something went wrong. Please try again later.";
}
mysqli_stmt_close($stmt);
}
// Close statement
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Sign Up</h2>
<p>Please fill this form to create an account.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control" value="<?php echo $password; ?>">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>">
<span class="help-block"><?php echo $confirm_password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
<p>Already have an account? Login here.</p>
</form>
</div>
</body>
</html>
Full config.php
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'users');
/* Attempt to connect to MySQL database */
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
My question is how to make the login.php logins the user.
The problem was that the password field wasn't long enough to hold the whole hash. I solved the issue by increasing the password field length from 48 to 8096. This solved the problem. Thanks to Dharman for pointing out the possible issue!
So, I have a login page (login.php)
<?php
// Initialize the session
session_start();
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: asdasd.php");
exit;
}
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = "Please enter username.";
} else{
$username = trim($_POST["username"]);
}
// Check if password is empty
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
} else{
$password = trim($_POST["password"]);
}
// Validate credentials
if(empty($username_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT id, felhasznalonev, jelszo FROM diakok WHERE felhasznalonev = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = $username;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Store result
mysqli_stmt_store_result($stmt);
// Check if username exists, if yes then verify password
if(mysqli_stmt_num_rows($stmt) == 1){
// Bind result variables
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
// Redirect user to welcome page
header("location: asdasd.php");
} else{
// Display an error message if password is not valid
$password_err = "The password you entered was not valid.";
}
}
} else{
// Display an error message if username doesn't exist
$username_err = "No account found with that username.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Login</h2>
<p>Please fill in your credentials to login.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Login">
</div>
<p>Don't have an account? Sign up now.</p>
</form>
</div>
</body>
</html>
With that, I can login to accounts which are created by felvetel.php:
<?php
$teljes_nev = $_POST['teljes_nev'];
$kategoria = $_POST['kategoria'];
$felhasznalonev = $_POST['felhasznalonev'];
$idcske = "NULL";
header("Content-type: text/html; charset=utf-8");
if (!$teljes_nev) {
echo "Kérem írja be a diák nevét.";
exit;
}
if(!get_magic_quotes_gpc()) {
$teljes_nev = addslashes($teljes_nev);
$felhasznalonev = addslashes($felhasznalonev);
$jelszo_alap = rand(1000,9999);
$jelszo = password_hash($jelszo_alap, PASSWORD_DEFAULT);
}
# $adatbazis = new mysqli('localhost', 'root', '', 'diakok');
$adatbazis->set_charset('utf8');
if (mysqli_connect_errno()) {
echo "Nem sikerült csatlakozni az adatbázishoz. (1-es hibakód)";
}
$lekerdezes = "INSERT INTO diakok VALUES
('".$felhasznalonev."', '".$teljes_nev."', '".$jelszo."', '".$kategoria."', '".$idcske."', '".$idcske."' , '".$idcske."' ,'".$idcske."', '".$idcske."')";
$talalat = $adatbazis->query($lekerdezes);
if ($talalat) {
echo $teljes_nev." nevű diák sikeresen felkerült az adatbázisba! (A diák jelszava ".$jelszo_alap.")";
} else {
echo "Hiba! A diákot nem sikerült hozzáadni az adatbázishoz.";
}
$adatbazis->close();
?>
My problem is that it says "The password you entered was not valid." while I write the correct password.
For example, I created a test user called admin.pelda and its password without password_hash() is 2161.
Now when I try to log in the account, it gives the invalid password message to me.
Any ideas to fix it?
(My config.php is okay)
The problem was that the hashed password is really long, and in the database, the password's max length was set to 15.
Got this error. Please can anyone help. I am a beginner at this.
Undefined variable: mysqli in C:\xampp\htdocs\final\register.php on line 20
Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\xampp\htdocs\final\register.php:20 Stack trace: #0 {main}
thrown in C:\xampp\htdocs\final\register.php on line 20
What do we need to do in order to validate the html form with some validation and how can we put the submitted details into the database table ?
This is the code of
Register.php
<?php
include "header.php";
// Include config file
require_once 'dbconfig.php';
// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT id FROM signup WHERE username = ?";
if($stmt = $mysqli->prepare($conn,$sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("s", $param_username);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
// store result
$stmt->store_result();
if($stmt->num_rows == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
}
// Validate password
if(empty(trim($_POST['password']))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST['password'])) < 6){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST['password']);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = 'Please confirm password.';
} else{
$confirm_password = trim($_POST['confirm_password']);
if($password != $confirm_password){
$confirm_password_err = 'Password did not match.';
}
}
// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
// Prepare an insert statement
$sql = "INSERT INTO signup (username, password) VALUES (?, ?)";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("ss", $param_username, $param_password);
// Set parameters
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
// Attempt to execute the prepared statement
if($stmt->execute()){
// Redirect to login page
header("location: login.php");
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
}
// Close connection
$mysqli->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{
width: 350px;
padding: 20px;
margin: 10px 10px 10px 10px;
}
</style>
</head>
<body>
<div class="jumbotron">
<div class="wrapper">
<h2>Sign Up</h2>
<p>Please fill this form to create an account.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username"class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control" value="<?php echo $password; ?>">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>">
<span class="help-block"><?php echo $confirm_password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
<p>Already have an account? Login here.</p>
</form>
</div>
</div>
</body>
</html>
if($stmt = mysqli_prepare($conn, $sql)){}
This line shows error. What is binding and how to use it?
Login.php
<?php
include 'header.php';
// Include config file
require_once 'dbconfig.php';
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = 'Please enter username.';
} else{
$username = trim($_POST["username"]);
}
// Check if password is empty
if(empty(trim($_POST['password']))){
$password_err = 'Please enter your password.';
} else{
$password = trim($_POST['password']);
}
// Validate credentials
if(empty($username_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT Username, Password FROM login WHERE Username = ?";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "a", $param_username);
// Set parameters
$param_username = $username;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Store result
mysqli_stmt_store_result($stmt);
// Check if username exists, if yes then verify password
if(mysqli_stmt_num_rows($stmt) == 1){
// Bind result variables
mysqli_stmt_bind_result($stmt, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
/* Password is correct, so start a new session and
save the username to the session */
session_start();
$_SESSION['username'] = $username;
header("location: welcome.php");
} else{
// Display an error message if password is not valid
$password_err = 'The password you entered was not valid.';
}
}
} else{
// Display an error message if username doesn't exist
$username_err = 'No account found with that username.';
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Login</h2>
<p>Please fill in your credentials to login.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username"class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Login">
</div>
<p>Don't have an account? Sign up now.</p>
</form>
</div>
</body>
</html>
register_val.php
<?php
require_once('dbconfig.php');
// function for email validation
function is_valid_email($email)
{
if (empty($email)) {
echo "Email is required.";
return false;
} else {
$email = test_input($email);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format.";
return false;
}
// now check if the mail is already registered
$slquery = "SELECT 2 FROM signup WHERE Email = '$email'";
$selectresult = mysql_query($slquery);
if(mysql_num_rows($selectresult)>0) {
echo 'This email already exists.';
return false;
}
// now returns the true- means you can proceed with this mail
return true;
}
// function for password verification
function is_valid_passwords($password,$confirm_password)
{
// Your validation code.
if (empty($password)) {
echo "Password is required.";
return false;
}
else if ($password != $confirm_password) {
// error matching passwords
echo 'Your passwords do not match. Please type carefully.';
return false;
}
// passwords match
return true;
}
// function for creating user
function create_user($email, $password, $confirm_passwordpassword)
{
$query = "INSERT INTO `singup` (email, password, confirmpassword) VALUES ('$email', '$password', '$cpassword')";
$result = mysql_query($query);
if($result){
return true; // Success
}else{
return false; // Error somewhere
}
}
// Code execution starts here when submit
if (isset($_POST['email']) && isset($_POST['password'])){
// Reading form values
$email = $_POST['email'];
$password = $_POST['password'];
$confirm_password = $_POST['confirmpassword'];
if (is_valid_email($email) && is_valid_passwords($password,$confirm_password))
{
if (create_user($email, $password, $cpassword)) {
echo 'New User Registered Successfully.';
}else{
echo 'Error Registering User!';
}
}
// You don't need to write another 'else' since this is the end of PHP code
?>
dbconfig.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername; dbname = 'car sale' ", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Have you created object $mysqli?
$mysqli = new Mysqli("host","db user","db password","db name");
Put it on Register.php before you call $mysqli
mysqli and PDO are different. Please refer https://www.w3schools.com/php/php_mysql_connect.asp
Your dbconfig.php will look like
<?
$host="127.0.0.1";
$port=3306;
$socket="";
$user="user";
$password="password";
$dbname="dbname";
$mysqli = new mysqli($host, $user, $password, $dbname, $port, $socket)
or die ('Could not connect to the database server' . mysqli_connect_error());
if($mysqli!=null){
//echo "Mysql connected. Yeah!<br/>";
$mysqli->close();
}
?>
Honestly this is a mess, you have
$conn = new PDO("mysql:host=$servername; dbname = 'car sale' ", $username, $password);
Then
$mysqli->prepare($conn,$sql)
Then (deprecated and removed in PHP7+)
$result = mysql_query($query);
And
$query = "INSERT INTO `singup` (email, password, confirmpassword) VALUES ('$email', '$password', '$cpassword')";
And
$slquery = "SELECT 2 FROM signup WHERE Email = '$email'";
SQLInjection issues. 3 different databases drivers. Um Start over?....
I would start by getting rid of all that DB junk, and use only one of them (Preferably PDO. :-) ).
Hey it does look like you go the login done fairly well, not querying the password, using a secure hash compare function. Checking for 1 and only one result. That's all good. The rest ... not so much.
It needs a lot of cleanup done, this is all simple stuff, but it's beyond the scope of one question.
Once you clean up the DB stuff you may find that this error evaporates... Because you are confused as to how you are connecting to the DB.
To be frank, it looks like a lot of Copy and pasted code. There is nothing wrong with that, but you have to understand what the code does on some level. Code is like handwriting, you can tell how well someone knows the language by how they write the code. I see maybe 4 different levels of coders at work here.
I hope my title makes sense, cause I don't know how to phrase it any shorter.
I am doing a login and sign up form with parameters and hashing. I have used parameters before but never in a signup form.
So the issue it that when I make a new a user it ONLY inserts the password but not the username. I have tried to change the name of the username, I have checked the connection to the database is correct and I am simply lost of what to do now.
My database can be seen here:
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT id FROM user WHERE username = ?";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Validate password
if(empty(trim($_POST['password']))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST['password'])) < 6){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST['password']);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = 'Please confirm password.';
} else{
$confirm_password = trim($_POST['confirm_password']);
if($password != $confirm_password){
$confirm_password_err = 'Password did not match.';
}
}
// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) &&
empty($confirm_password_err)){
// Prepare an insert statement
$sql = "INSERT INTO user (name, password) VALUES (?, ?)";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $param_username,
$param_password);
// Set parameters
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT);
// Creates a password hash
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
// header("location: login.php");
echo "You have been added";
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($conn);
}
?>
<?php
include "header.php";
?>
<div class="wrapper">
<h2>Sign Up</h2>
<p>Please fill this form to create an account.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?
>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ?
'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username"class="form-control"
value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?>
</span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ?
'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control"
value="<?php echo $password; ?>">
<span class="help-block"><?php echo $password_err; ?>
</span>
</div>
<div class="form-group <?php echo
(!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-
control" value="<?php echo $confirm_password; ?>">
<span class="help-block"><?php echo $confirm_password_err;
?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary"
value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
<p>Already have an account? Login here.
</p>
</form>
</div>
<footer>
<?php
include "footer.php";
?> </footer>
Hope you can help me, feel free to ask questions if I haven't made myself clear enough :)
Remove the following line
$param_username = $username;
Because you overwrite $param_username that is already set with trim($_POST["username"])
Have a nice day.
It turnes out the $username = $password = $confirm_password = ""; was clearing my textbox so I removed it and added a $username = $_POST["username"]; and then the code worked.