Basic question but I keep failing. Have checked out similar topics but didn't get closer to the solution, so please don't redirect me just point out what I'm missing. Thank you.
<?php
$hashed_password = "";
$con = mysqli_connect("localhost", "root", "", "testTable");
if (isset($_POST["reg_button"])){
$password = ($_POST["reg_password"]);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$query = mysqli_query($con, "INSERT INTO user VALUES('', '$hashed_password')");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>register</title>
</head>
<body>
<form action="register.php" method="POST">
<input type="password" name="reg_password" placeholder="Password">
<br><br>
<input type="submit" name="reg_button" value="Register">
</form>
<br>
<form action="login.php" method="POST">
<input type="password" name="login_password" placeholder="Password">
<br><br>
<input type="submit" name="login_button" value="Login">
</form>
</body>
</html>
This is the registering part and it is working flawlessly. The provided password is getting hased and stored in the DB.
<?php
include "register.php";
$con = mysqli_connect("localhost", "root", "", "testTable");
if(isset($_POST["login_button"])){
$password = password_verify($_POST["login_password"], $hashed_password);
$checkDB = mysqli_query($con, "SELECT * FROM user WHERE password = '$password'");
$checkLogin = mysqli_num_rows($checkDB);
if($checkLogin == 1){
$row = mysqli_fetch_array($checkDB);
echo "Welcome";
}
else {
echo "Password incorrect";
}
}
?>
This is the login part and it always fails. I suspect the following snippet to be the culprit:
$password = password_verify($_POST["login_password"], $hashed_password);
but have no idea how to fix it.
Any help would be great. Thank you!
UPDATED CODE:
register.php:
<?php
$hashed_password = "";
$name = "";
$con = mysqli_connect("localhost", "root", "", "testTable");
if (isset($_POST["reg_button"])){
$password = ($_POST["reg_password"]);
$name = ($_POST["reg_name"]);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$query = mysqli_query($con, "INSERT INTO user VALUES('', '$name','$hashed_password')");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>register</title>
</head>
<body>
<form action="register.php" method="POST">
<input type="text" name="reg_name" placeholder="Name">
<br><br>
<input type="password" name="reg_password" placeholder="Password">
<br><br>
<input type="submit" name="reg_button" value="Register">
</form>
<br>
<form action="login.php" method="POST">
<input type="text" name="login_name" placeholder="Name">
<br><br>
<input type="password" name="login_password" placeholder="Password">
<br><br>
<input type="submit" name="login_button" value="Login">
</form>
</body>
</html>
login.php:
<?php
include "register.php";
$con = mysqli_connect("localhost", "root", "", "testTable");
if(isset($_POST["login_button"])){
$name = $_POST['login_name'];
$password = $_POST['login_password'];
$checkDB = mysqli_query($con, "SELECT * FROM user WHERE name = '$name'");
$passwordField = null;
while($getRow = mysqli_num_rows($checkDB)){
$passwordField = $getRow['password']; // Get hashed password
}
if(password_verify($password, $passwordField)){
echo('Correct');
}else{
echo('Wrong');
}
}
?>
Below from where do you get $hashed_password?Even if you included register.php,it doenst do anything,since those values are not set.
$password = password_verify($_POST["login_password"], $hashed_password);
You first need to get it from the db.
Second, password_verify returns true or false so even if $hashed_password is set,$password would be a boolean.
You can do this via while loop and mysqli_fetch_array(). That must solve your problem.: [UPDATED]
<?php
$con = mysqli_connect("localhost", "root", "", "testtable");
if(isset($_POST["login_button"])){
// $password = password_verify($_POST["login_password"], $hashed_password);
$password = $_POST['password'];
$checkDB = mysqli_query($con, "SELECT * FROM user");
while($getRow = mysqli_fetch_array($checkDB)){
$passwordRow = $getRow['password'];
}
if(password_verify($password, $passwordRow) === TRUE){
echo('Welcome');
}else{
echo('Wrong credentials');
}
}
?>
Related
I need to сheck if username is already taken or not. And if it is ok, to redirect to another page but if not (here I am stuck) to make the "username is already taken" appear under the input line.
there is my php code:
<?php
$host = "localhost";
$dbusername = "postgres";
$dbpassword = "admroot";
$db = "local_db_server_test";
$con = pg_connect("host=$host dbname=$db user=$dbusername password=$dbpassword") or die ("Could not connect to Server\n");
if(!$con){ die('Error: Unable to open database'); }
else {
$username = $_POST['username'];
$password = $_POST['password'];
if(strlen($password) < 6) {
pg_close($con); // also can use die() but without header and redirection
header("Location:sign_up_pass_err.html");
}
$query = "INSERT INTO register(username, password) VALUES ('$username',crypt('$password',gen_salt('md5')))";
$result = pg_query($con, $query);
header("Location: login.html");
}
pg_close($con);
?>
And this is my html code:
<!DOCTYPE html>
<html>
<head></head>
<body>
<form action="sign_up.php" method="post">
<input type="text" name="username" placeholder="Username" required><br><br>
<input type="password" name="password" placeholder="Password" required><br><br>
<input type="submit" value="Sign up">
</form>
</body>
</html>
I am fiddling around with mysql, PHP, and phpMyAdmin and I am making a short little test login and register system. Only problem is for some reason, the register button takes me to the login page, which it's supposed to, but localhost crashes for some reason. Any help?
Edit: You can test it out too if you would like. My Site: http://localhost/
index.php
<head>
<meta charset="utf-8">
<title>Test Site</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<form action="login/logreg.php" method="post" accept-charset="utf-8">
<label>Username: </label><input type="text" name="username" value="" placeholder="Username">
<br><br>
<label>Password: </label><input type="password" name="password" value="" placeholder="Password">
<br><br>
<input type="submit" name="login" value="Login">
<input type="submit" name="register" value="Register">
</form>
</body>
logreg.php
<?php
$cookie_name = "loggedin";
$servername = "localhost";
$username = "root";
$password = "H2124130E63C8D14871";
$database = "webserver";
$conn = mysqli_connect($servername, $username, $password $database);
if (!$conn) {
die("Database Connection Failed: ".mysqli_connect_error());
}
if (isset($_POST['login']))
{
$user = $_POST['username'];
$pass = $_POST['password'];
$phash = sha1(sha1($pass."salt")."salt");
$sql = "SELECT * FROM users WHERE username='$user' AND password='$phash';";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if ($count == 1)
{
$cookie_value = $user;
setcookie($cookie_name, $cookie_value, time() + (180), "/");
header("Location: personal.php");
}
else
{
echo "Username Or Password Is Incorrect!";
}
}
else if (isset($_POST['register']))
{
$user = $_POST['username'];
$pass = $_POST['password'];
$phash = sha1(sha1($pass."salt")."salt");
$sql = "INSERT INTO users (id, username, password) VALUES ('', '$user', '$phash');";
$result = mysqli_query($conn, $sql);
}
?>
personal.php
<?php
$cookie_name = "loggedin";
if (isset($_COOKIE[$cookie_name]))
{
$cookie_value = $_COOKIE[$cookie_name];
echo "Welcome To Your Personal Area $cookie_value!";
echo 'Logout';
}
?>
logout.php
<?php
setcookie("loggedin", "val", time() - (120), "/");
header("Location: index.php");
?>
You missed a comma here:
$conn = mysqli_connect($servername, $username, $password $database);
I've created a login/registration system and the registration part is working fine. However, now I am trying to login and when you login it should start a session and redirect you to account.php page but it's not doing that. It's just refreshing the page and doing nothing else.
Index page:
<?php
include 'dbh.php';
session_start();
if(isset($_SESSION['id'])){
$result = $conn->query("SELECT * FROM users where id=".$_SESSION['id']);
$row = $result->fetch_array(MYSQLI_BOTH);
}
# REGISTRATION HANDLER
if(isset($_POST['rsubmit'])){
$username = $_POST['username'];
$email = $_POST['email'];
$plainpass = $_POST['password'];
$password = password_hash($plainpass, PASSWORD_BCRYPT, array('cost' => 10));
$sql = "INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$password')";
$result = mysqli_query($conn, $sql);
$btn = "Account created! Please login";
}else {
$btn = "Register";
}
# LOGIN HANDLER
if(isset($_POST['lsubmit'])){
$lemail = $_POST['lemail'];
$lpassword = $_POST['lpassword'];
$result = $conn->query("SELECT * FROM users where email='$lemail'");
$row = $result->fetch_array(MYSQLI_BOTH);
if(password_verify($lpassword, $row['password'])){
$_SESSION['id'] = $row['id'];
Header("Location: account.php");
}
} else {
}
?>
<html>
<head>
<meta charset="UTF-8">
<title>Liam4Life</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="login-page">
<div class="form">
<form class="register-form" action="index.php" method="POST">
<input required name="username" type="text" placeholder="Username"/>
<input required name="rpassword" type="password" placeholder="Password"/>
<input required name="remail" type="email" placeholder="Email address"/>
<button>Register</button>
<p class="message">Already registered? Sign In</p>
</form>
<form class="login-form" action="index.php" method="POST">
<input required name="lemail" type="email" placeholder="Email"/>
<input required name="lpassword" type="password" placeholder="Password"/>
<button type="submit" name="lsubmit">Login</button>
<p class="message">Not registered? Create an account</p>
</form>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
DBH.php:
<?php
$conn = mysqli_connect("localhost", "root", "", "game");
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
if(isset($_SESSION['id'])){
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
$_SESSION['password'] = $row['password'];
}
?>
Instead of Header("Location: account.php");
use the following statement
echo "<script>location.href='account.php'</script>";exit;
The issue as mentioned by Jeff, it can be due to space the redirection is not happening. If the above logic works. Then remove additional space in config / else need to add session_start() as the first line of statement in your index.php file and have the header("Location: account.php") logic.
Note: To debug, ensure the control goes here by printing and adding a exit statement.
try
Index page:
<?php
session_start();
include 'dbh.php';
-----code---------
?>
DBH.php:
<?php
session_start();
-----code---------
?>
//session_start(); needed to give top of page and here it is missing in DBH.php. Hence $_SESSION not working
Try next approach:
<?php
session_start();
$conn = mysqli_connect("localhost", "root", "", "game");
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
if(!empty($_SESSION['id'])){
$result = $conn->query("SELECT * FROM users where id=".(int)$_SESSION['id']);
if(!$result->num_rows) {
session_destroy();
Header("Refresh:0");
exit;
}
Header("Location: account.php");
exit;
}
# LOGIN HANDLER
if(isset($_POST['lsubmit']) && !empty($_POST['lemail'])){
$lemail = mysqli_real_escape_string($_POST['lemail']);
$result = $conn->query("SELECT * FROM users where email='{$lemail}'");
$row = $result->fetch_array(MYSQLI_BOTH);
if(password_verify($_POST['lpassword'], $row['password'])){
$_SESSION['id'] = $row['id'];
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
$_SESSION['password'] = $row['password'];
Header("Location: account.php");
exit;
}
}
# REGISTRATION HANDLER
elseif(isset($_POST['rsubmit']) && !empty($_POST['email'])){
$username = mysqli_real_escape_string($_POST['username']);
$email = mysqli_real_escape_string($_POST['email']);
$password = password_hash($_POST['password'], PASSWORD_BCRYPT, array('cost' => 10));
$result = $conn->query("INSERT INTO users (username, email, password) VALUES ('{$username}', '{$email}', '{$password}')");
$btn = "Account created! Please login";
}
?>
<html>
<head>
<meta charset="UTF-8">
<title>Liam4Life</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="login-page">
<div class="form">
<form class="register-form" action="index.php" method="POST">
<input required name="username" type="text" placeholder="Username"/>
<input required name="rpassword" type="password" placeholder="Password"/>
<input required name="remail" type="email" placeholder="Email address"/>
<button>Register</button>
<p class="message">Already registered? Sign In</p>
</form>
<form class="login-form" action="index.php" method="POST">
<input required name="lemail" type="email" placeholder="Email"/>
<input required name="lpassword" type="password" placeholder="Password"/>
<button type="submit" name="lsubmit">Login</button>
<p class="message">Not registered? Create an account</p>
</form>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
I have a little problem with my Login & Register System but I don't know where the problem is. When I press "Login" or "Register", the next page is white. I see only my message: "Try again!". I made 3 PHP files:
1) index.php
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="logreg.php" metodh="post" accept-charset="utf-8">
<label>Username:</label><input type="text" name="username" placeholder="Username">
<br>
<label>Password:</label><input type="password" name="password" placeholder="Password">
<br>
<input type="submit" name="login" value="Login">
<input type="submit" name="register" value="Register">
</form>
</body>
</html>
I think the problem is in the next file:
2) logreg.php
<?php
$servername = "localhost";
$username = "alex";
$password = "calamar28";
$database = "register/login";
$conn = mysqli_connect($servername, $username, $password, $database );
if(!$conn){
die("Connection failde:".mysqli_connect_error());
}
if(isset($_POST["login"])) {
$user = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='$user' AND password='$pass';";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if ($count == 1)
{
header("Location: personal.php");
}
else
{
echo "Username or password is incorrect!";
}
}
else if(isset($_POST["register"])) {
$user = $_POST['username'];
$pass = $_POST['password'];
$sql = "INSERT INTO users (id, username, password) VALUES ('', '$user', '$pass')";
$result = mysqli_query($conn, $sql);
}
else
{
echo "Try again!";
}
?>
3) personal.php
<?php
if(isset($_POST["login"])){
echo "Welcome to you personal area !";
echo 'Your proiect';
}
else
{
echo "You are not logged in!";
}
?>
You will also need to set some session variables to carry through onto the personal.php page... This will help determine if the user has logged in successfully or not as the original posted data won't be transferred through when you redirect to this page... You'll want your logreg.php to be the following:
<?php
if (!isset($_SESSION)) {session_start();}
$servername = "localhost";
$username = "alex";
$password = "calamar28";
$database = "register/login";
$conn = mysqli_connect($servername, $username, $password, $database );
if(!$conn){
die("Connection failde:".mysqli_connect_error());
}
if(isset($_POST["login"])) {
$user = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='$user' AND password='$pass';";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if ($count == 1)
{
$_SESSION['loggedIn'] = 1;
header("Location: personal.php");
}
else
{
echo "Username or password is incorrect!";
}
}
else if(isset($_POST["register"])) {
$user = $_POST['username'];
$pass = $_POST['password'];
$sql = "INSERT INTO users (id, username, password) VALUES ('', '$user', '$pass')";
$result = mysqli_query($conn, $sql);
}
else
{
echo "Try again!";
}
?>
And then your personal.php page will change to the following:
<?php
if (!isset($_SESSION)) {session_start();}
if(isset($_SESSION["loggedIn"]) && ($_SESSION["loggedIn"] == 1) ){
echo "Welcome to you personal area !";
echo 'Your proiect';
}
else
{
echo "You are not logged in!";
}
?>
The Default Method for HTML Forms is GET. And in your HTML Code you wrote metodh instead of method. This would be ignored and then your method would automatically default to GET. Other than this, your PHP Code is fine.
Change your HTML Code to look something like below and everything should work fine as expected:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="logreg.php" method="post" accept-charset="utf-8">
<label>Username:</label><input type="text" name="username" placeholder="Username">
<br>
<label>Password:</label><input type="password" name="password" placeholder="Password">
<br>
<input type="submit" name="login" value="Login">
<input type="submit" name="register" value="Register">
</form>
</body>
</html>
Hello I am having some issue here i created a script to update users account details but when the form is filled in and submit button clicked no errors come up but at the same time no changes are made in the table
THIS IS ONLY A DUMMY APPLICATION SO EVERYTHING IS KEEP BASIC
<?php
session_start();
include('connect_mysql.php');
if(isset($_POST['update']))
{
$usernameNew = stripslashes(mysql_real_escape_string($_POST["username"]));
$passwordNew = stripslashes(mysql_real_escape_string($_POST["password"]));
$first_nameNew = stripslashes(mysql_real_escape_string($_POST["first_name"]));
$last_nameNew = stripslashes(mysql_real_escape_string($_POST["last_name"]));
$emailNew = stripslashes(mysql_real_escape_string($_POST["email"]));
$user_id = $_SESSION['user_id'];
$editQuery = mysql_query("UPDATE users SET username='$usernameNew', password='$passwordNew', first_name='$first_nameNew', last_name='$last_nameNew' , email='$emailNew' WHERE user_id='$user_id'");
if(!$editQuery)
{
echo mysql_error($editQuery);
die($editQuery);
}
}
?>
<html>
<head>
<title>Edit Account</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
<header><h1>E-Shop</h1></header>
<article>
<h1>Welcome</h1>
<h1>Edit Account</h1>
<div id="login">
<ul id="login">
<form method="post" name="editAccount" action="userEditAccount.php" >
<fieldset>
<legend>Fill in the form</legend>
<label>Select Username : <input type="text" name="username" /></label>
<label>Password : <input type="password" name="password" /></label>
<label>Enter First Name : <input type="text" name="first_name" /></label>
<label>Enter Last Name : <input type="text" name="last_name" /></label>
<label>Enter E-mail Address: <input type="text" name="email" /></label>
</fieldset>
<br />
<input type="submit" value="Edit Account" class="button">
<input type="hidden" name="update" value="update">
</form>
</div>
<form action="userhome.php" method="post">
<div id="login">
<ul id="login">
<li>
<input type="submit" value="back" onclick="index.php" class="button">
</li>
</ul>
</div>
</article>
<aside>
</aside>
<div id="footer">Text</div>
</div>
</body>
</html>
SOrry for some reason the I forgotten to copy this part faceslap
login.php:
<?php
session_start();
require('connect_mysql.php');
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$username = $_POST["username"];
$password = $_POST["password"];
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$query = mysql_query("SELECT * FROM users WHERE Username='$username' AND Password='$password'");
$numrow = mysql_num_rows($query);
if($username && $password){
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrow = mysql_num_rows($query);
if($numrow !=0){
while($row = mysql_fetch_assoc($query)){
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if($username == $dbusername && $password == $dbpassword ){
$_SESSION['user_id'] = $user_id;
header("Location: userhome.php");
}
else{
echo "Incorect password";
}
}
else{
die("This user dosent exists");
}
}
else{
$reg = die("Please enter username and password");
}
}
?>
You haven't called session_start() at the beginning of the file, so $username will be an empty string, and the update command will only update rows where the username is an empty string.
Edit: In fact, that code won't even be run, because you haven't called session_start(), isset($_SESSION['update']) will evaluate to false.
Did you mean to write $_SESSION['update']? Shouldn't that be $_POST['update']?
Last but not least, personally I would replace this:
<input name="update" type="submit" submit="submit" value="Edit Account" class="button">
with this:
<input type="submit" value="Edit Account" class="button">
<input type="hidden" name="update" value="update">
At least for clarity. I don't know if it's still the case, but in time gone by not all browsers submitted the name/value of the submit button.
Sir from the code given above i think you have error in your login.php
$_SESSION['user_id'] = $user_id;
You are not assigning value to $user_id that why it is setting blank value to $_SESSION['user_id'].
<?php
session_start();
require('connect_mysql.php');
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$username = $_POST["username"];
$password = $_POST["password"];
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$query = mysql_query("SELECT * FROM users WHERE Username='$username' AND Password='$password'");
$numrow = mysql_num_rows($query);
if($username && $password){
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrow = mysql_num_rows($query);
if($numrow !=0){
$user_id = 0;
while($row = mysql_fetch_assoc($query)){
$dbusername = $row['username'];
$dbpassword = $row['password'];
$user_id = $row['user_id'];
}
if($username == $dbusername && $password == $dbpassword ){
$_SESSION['user_id'] = $user_id;
header("Location: userhome.php");
}
else{
echo "Incorect password";
}
}
else{
die("This user dosent exists");
}
}
else{
$reg = die("Please enter username and password");
}
}
?>