$stmt -> execute() returning false - php

I've tried debuggind this issue for almost 4 hours with no luck. No error messages, $stmt -> execute() gives false for whatever reason that I do not know of.
register.php
<?php
session_start();
if( isset($_SESSION['id'])){
header("Location: index.php");
}
require 'database.php';
$message = '';
if(!empty($_POST['user']) && !empty($_POST['password'])):
$pass = $_POST['password'];
$user = $_POST['user'];
$sql = "Insert into user (username, password) values (:user, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':user', $_POST['user']);
$stmt->bindValue(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
//var_dump($_POST['password']);
//var_dump($_POST['user']);
if($stmt -> execute()):
$message = 'Successfully created new user';
else:
$message = 'Sorry there must have been an issue creating your account';
endif;
endif;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Register Below</title>
</head>
<body>
<?php if(!empty($message)): ?>
<p><?= $message ?></p>
<?php endif; ?>
<h1>Register</h1>
<form class="" action="register.php" method="post">
<input type="text" placeholder="Username" name="user" id="user">
<input type="password" placeholder="and password" name="password" id="password">
<input type="password" placeholder="confirm password" name="confirm_password">
<button type="submit" name="button">Register</button>
</form>
home
</body>
</html>
database.php
<?php
$server = 'localhost';
$username ='master';
$password ='master';
$database = 'quiz';
try{
$conn = new PDO("mysql:host=$server;dbname=$database;" , $username, $password);
} catch(PDOException $e){
die ("Connection failed" . $e->getMessage());
}
?>
I know I am ignoring the confirm password, but I want to make sure I can insert into the database first.

Solution: my password length was 15 in my database... hashed password >> 15 characters. Changed the length to 255 and it's all good. Hopefully this will be useful for someone else.

Related

Getting error Strict Standards: Only variables should be passed by reference in register.php on line 20

I downloaded login php script from GitHub (Link to it) and when I try to register, it displays me this error: Strict Standards: Only variables should be passed by reference in /homework/register.php on line 20
On login page it doesn't show any errors.
Code that I was using:
<?php
session_start();
if( isset($_SESSION['user_id']) ){
header("Location: /");
}
require 'database.php';
$message = '';
if(!empty($_POST['email']) && !empty($_POST['password'])):
// Enter the new user in the database
$sql = "INSERT INTO users (email, password) VALUES (:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
if( $stmt->execute() ):
$message = 'Successfully created new user';
else:
$message = 'Sorry there must have been an issue creating your account';
endif;
endif;
?>
<!DOCTYPE html>
<html>
<head>
<title>Register Below</title>
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
<link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="header">
Homework
</div>
<?php if(!empty($message)): ?>
<p><?= $message ?></p>
<?php endif; ?>
<h1>Register</h1>
<span>or login here</span>
<form action="register.php" method="POST">
<input type="text" placeholder="Enter your email" name="email">
<input type="password" placeholder="and password" name="password">
<input type="password" placeholder="confirm password" name="confirm_password">
<input type="submit">
</form>
</body>
</html>
database.php (if needed):
<?php
$server = 'localhost';
$username = 'my_username';
$password = 'my_password';
$database = 'my_dbname';
try{
$conn = new PDO("mysql:host=$server;dbname=$database;", $username, $password);
} catch(PDOException $e){
die( "Connection failed: " . $e->getMessage());
}
Database is working fine. Not getting errors.
Can someone explain what is going wrong with registration?
When passing a value to bind_param(), you need to pass a variable and not the return value from a function...
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
to...
$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$stmt->bindParam(':password', $password);
When you see a parameter with a & in front of it as in &$variable in...
public bool PDOStatement::bindParam ( mixed $parameter , mixed
&$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed
$driver_options ]]] )
You need to pass a variable.

php password_hash and password_verify fail

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');
}
}
?>

PHP registration form in mysql

I am having problem in when I building the registration form with php and mysq.
I have two files, contactus.php and home.php.
The code for contactus.php is below:
<?php
session_start();
$db = mysqli_connect("localhost", "wadca2user", "password123", "p1514432db");
if(isset($_POST['register_btn'])){
session_start();
$username = mysql_real_escape_string($_POST['username']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$password2 = mysql_real_escape_string($_POST['password2']);
if($password == $password2){
$password = md5($password); // stored before
$sql = "INSERT INTO users(username,email,password) Values('$username','$email','$password')";
mysqli_query($db, $sql);
$_SESSION['message'] = "Your are now logged in";
$_SESSION['username'] = $username;
header("location: home.php");
}else{
$_SESSION['message'] = "The two passwords do not match";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link href="css/maincss.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="header">
<h1>Register</h1>
</div>
<form method="post" action="contactus.php">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="username" class="textInput"></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="email" name="email" class="textInput"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" class="textInput"></td>
</tr>
<tr>
<td>Password again:</td>
<td><input type="password" name="password2" class="textInput"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="register_btn" value="Register"></td>
</tr>
</table>
</form>
</body>
</html>
The code for home.php is below:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<link href="css/maincss.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="header">
<h1>Register</h1>
</div>
<h1>Home</h1>
<div>
<h3>Welcome<?php echo $_SESSION['username']; ?></h3>
</div>
</body>
</html>
After I click on submit, it is supposed to go to home.php. However, it does not succeed. I am not sure where is my problem.
Here is mysql 'users' table
Use PDO, this (below) should do the job, it's secure against sql injection (check prepared request for more).
You must not use MD5, it's deprecated, try sha1() or sha256().
Edit : you also have password_hash() which is quite nice.
<?php
session_start();
$servername = "localhost";
$username = "wadca2user";
$password = "password123";
$conn = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=p1514432db", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
if(isset($_POST['register_btn']) && !is_null($conn)){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
if($password === $password2){
$password = md5($password); // stored before
$request = $conn->prepare("INSERT INTO users (username,email,password) VALUES (:username, :email, :password)");
$request->bindParam(':username', $username);
$request->bindParam(':email', $email);
$request->bindParam(':password', $password);
$request->execute();
$_SESSION['message'] = "Your are now logged in";
$_SESSION['username'] = $username;
header("location: home.php");
}else{
$_SESSION['message'] = "The two passwords do not match";
}
}
?>

Database insert not working (MySQL, PHP)

I have this PHP that basically is being used for inserting an email and password into an SQL database:
<?php
error_reporting(E_ALL ^ E_STRICT);
require "database.php";
$message = '';
if (!empty($_POST["email"]) &&!empty($_POST["password"])):
//Enter the new user in the database
$sql = "INSERT INTO users (email, password) VALUES (:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":email", $_POST['email']);
$stmt->bindParam(":password", password_hash($_POST['password'], PASSWORD_BCRYPT));
if ($stmt->execute() ):
$message = 'Successfully created a new user';
else:
$message = 'Sorry there must have been an issue whilst registering';
endif;
endif;
?>
Here is the form:
<div class="jumbotron" id="jumbotron-6">
<div class="container text-center">
<?php if (!empty($message)):
?>
<h3 id="h3message"><?= $message ?> </h3>
<?php endif; ?>
<form action="signup.php" method="POST">
<input type="text" placeholder="enter your email" name="email">
<input type="password" placeholder="and password" name="password">
<input type="password" placeholder="confirm password" name="confirm_password">
<input type="submit">
</form>
</div>
</div>
It doesn't insert into the database (all the fields, variables are correct i think - just email and password) and it comes back with the error message that I created that says 'Sorry there must have been an issue whilst registering'
Here is the database.php file
<?php
$server = 'localhost';
$username = "root";
$password = "";
$database = "auth";
try{
$conn = new PDO ("mysql:host={$server};dbname={$database};" , $username, $password);
}
catch (PDOException $e) {
die ( "Connection failed; " . $e->getMessage());
}
?>
Hash the password before you bind it:
$UserPWHash = password_hash($_POST['password'], PASSWORD_BCRYPT);
$stmt->bindParam(":password", $UserPWHash));

Login form PHP using PDO statements

I am creating a signup and login form. In signup form i am taking inputs from the users and storing those inputs in my database. I want when user input username and password in nss-login.php then it compares from the database whether that username and password is available in database or not. If credentials are available then it redirects to nss-admin.php.
However, current code doesn't seem to be working for whatever, everything seems okay logically. I am fairly new to php about two weeks so obviously I'm missing something. I've been looking around to see what I am doing wrong but still can't figure it out, so I am posting here as a last resort. I appreciate you taking the time to view my question.
Please make the required changes in code files and rectify errors where necessary.
This is nss-functions.php
<?php
include 'nss-config.php';
function connect($config) {
try {
$conn = new PDO('mysql:host=localhost; dbname='.$config['database'],
$config['username'],$config['password']);
$conn -> setAttribute(PDO :: ATTR_ERRMODE, PDO:: ERRMODE_EXCEPTION);
return $conn;
}
catch (Exception $e) {
return false;
}
}
function query($query,$bindings,$conn)
{
$stmnt = $conn->prepare($query);
$stmnt->execute($bindings);
return ($stmnt->rowCount() > 0) ? $stmnt : false;
}
?>
This is nss-signup.php
<!doctype html>
<html>
<head>
<title>Create a Free Account</title>
</head>
<body>
<?php
include 'nss-functions.php';
$conn=connect($config);
if (!$conn) die('Problem connecting to db.');
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$repass = $_POST['repass'];
if(empty($username) || empty($email) || empty($password) || empty($repass)) {
echo "Please fill all inputs correctly";
}
else {
if($repass == $password) {
query("insert into users(username,email,password) values(:username, :email , :password)",
array('username' => $username, 'email' => $email , 'password' => $password) , $conn);
echo "Your account is successfully created";
}
else {
echo "Fill password correctly";
}
}
}
?>
<form action="nss-signup.php" method="post">
<h1>Create Your Account</h1>
<p><label for="username">Username</label>
<input type="text" id="username" name="username" /></p>
<p><label for="email">Email Address</label>
<input type="text" id="email" name="email" /></p>
<p><label for="password">Choose a Password</label>
<input type="password" id="password" name="password" /></p>
<p><label for="repass">Confirm Password</label>
<input type="password" id="repass" name="repass" /></p>
<p><input type="submit" value="Submit" name="loginform" /></p>
</form>
</body>
</html>
This is nss-login.php
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<?php
include 'nss-validate.php';
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$user = $_POST['username'];
$pass = $_POST['password'];
if(validate($user,$pass)) {
$_SESSION['user'] = $user;
header("Location:nss-admin.php");
}
else {
echo "Incorrect credentials";
}
}
?>
<form action="nss-login.php" method="post">
<h1>Sign in to Your Account</h1>
<p><label for="username">Username</label>
<input type="text" id="username" name="username" /></p>
<p><label for="password">Your Password</label>
<input type="password" id="password" name="password" /></p>
<p><input type="submit" value="Submit" name="loginform" /></p>
<p>Don't have an account? Create one.</p>
</form>
</body>
</html>
This is nss-validate.php
<?php
include 'nss-functions.php';
function validate($username,$password) {
$x = query("select username from users where username = :username", // variable for username
array('username' => $username) , $conn);
$y = query("select password from users where password = :password", // variable for password
array('password' => $password) , $conn);
return ($username == $x && $password == $y);
}
?>
This is nss-admin.php
<?php require 'nss-login.php'; ?>
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Hello, <?= $_SESSION['user']; ?></h1>
<h3>logout</h3>
</body>
</html>
$conn does not exist in the variable scope of your validate() function.
Change your function definition to this:
function validate($username,$password, $conn) {
and call it accordingly.
Note: Your validate function is completly useless. It will log everybody in with an existing password of any other user (if works at all, what I doubt). Also, you seem to store the password in plain text in the database.

Categories