PHP errors on form - php

So I have two files, one is index.php and register.php. Index is the form and register is the PHP handling the form. So here's index.php
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<form class="form-signin" role="form" action="register.php" method="post">
<h2 class="form-signin-heading">Please sign up</h2>
<input type="text" class="form-control" placeholder="Name" name="name" autofocus style="border-color:#<?php ?>;">
<input type="text" class="form-control" placeholder="Username" name="username" autofocus>
<input type="text" class="form-control" placeholder="Email" name="email" autofocus>
<input type="password" class="form-control" placeholder="Password" name="password">
<input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
</form>
</div>
</body>
</html>
And my register.php
<?php
try {
$handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
exit($e->getMessage());
}
//Post
$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password1 = $_POST['passwordconf'];
$ip = $_SERVER['REMOTE_ADDR'];
//Verifcation
if (empty($name) || empty($username) || empty($email) || empty($password) || empty($password1))
{
echo "Complete all fields";
}
// Password match
if ($password != $password1)
{
echo $passmatch = "Passwords don't match";
}
// Email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo $emailvalid = "Enter a valid email";
}
// Password length
if (strlen($password) <= 6){
echo $passlength = "Choose a password longer then 6 character";
}
if(empty($passmatch) && empty($emailvalid) && empty($passlength)) {
//Securly insert into database
$sql = 'INSERT INTO userinfo (name ,username, email, password, ip) VALUES (:name,:username,:email,:password,:ip)';
$query = $handler->prepare($sql);
$query->execute(array(
':name' => $name,
':username' => $username,
':email' => $email,
':password' => $password,
':ip' => $ip
));
}
?>
But here's what I want to do, I want to display the PHP errors alongside the form instead of having them displayed on register.php But I also want to use two separate files. Instead of combining the two files together. Any ideas?

I seriously don't understand your use of server side to do all these validations. It is wise and economical to do this in the client side itself. There are a hell lot of plugins for client side form validation, if that's the case for you.
A few scripts would be:
jQuery Form Validator
jQuery Validation Plugin
jQuery plugin: Validation
10 jQuery Form Validation Techniques and Tutorials
Find the last link to do the work yourself.
In your case, please try to separate the view and logic. It is also wise to follow Model-View-Controller architecture that is followed in many of the PHP Web Applications and JavaScript Apps now-a-days.
Or if you somehow need the logic to be done in server side, separate the form by putting the HTML inside form.php. And in your validation, do a small change, by including a flag, which is set to false, when the form is not validated.
Now, if the validation is not successful, i.e., the flag $valid = false, then you include the form.inc, else include success.inc.
if ($valid)
include 'success.inc';
else
include 'form.inc';
And since it is going to be in the same file, in the form.inc, add this line:
if (!$valid)
echo '<p class="error">You have errors in your form! Please correct them!</p>';

At the bottom of register.php simply call:
include 'index.php';
And your form will be displayed.
Add a line to display errors in your index.php:
<?php if (!empty($error)) { ?>
<?php echo "error occured: ".$error; ?>
<?php } ?>
This is a style of MVC programming (Model-View-Controller). The idea is not to echo things all over the place within register.php, instead you build up an application state in a model and then the view (index.php) reads from the model.

Try this out:
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<?php
if(isset($_POST['submit'])){
try {
$handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
exit($e->getMessage());
}
//Post
$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password1 = $_POST['passwordconf'];
$ip = $_SERVER['REMOTE_ADDR'];
//Verifcation
if (empty($name) || empty($username) || empty($email) || empty($password) || empty($password1))
{
echo "Complete all fields";
} if ($password != $password1)
{
echo $passmatch = "Passwords don't match";
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo $emailvalid = "Enter a valid email";
} else if (strlen($password) <= 6){
echo $passlength = "Choose a password longer then 6 character";
} if(empty($passmatch) && empty($emailvalid) && empty($passlength)) { // You don't need this line, you already checked above if these POST variables were empty.
//Securly insert into database
$sql = 'INSERT INTO userinfo (name ,username, email, password, ip) VALUES (:name,:username,:email,:password,:ip)';
$query = $handler->prepare($sql);
$query->execute(array(
':name' => $name,
':username' => $username,
':email' => $email,
':password' => $password,
':ip' => $ip
));
}
}
?>
<form class="form-signin" role="form" action="" method="post">
<h2 class="form-signin-heading">Please sign up</h2>
<input type="text" class="form-control" placeholder="Name" name="name" autofocus style="border-color:#<?php ?>;">
<input type="text" class="form-control" placeholder="Username" name="username" autofocus>
<input type="text" class="form-control" placeholder="Email" name="email" autofocus>
<input type="password" class="form-control" placeholder="Password" name="password">
<input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
<button class="btn btn-lg btn-primary btn-block" name='submit' type="submit">Sign up</button>
</form>
</div>
</body>
</html>
Few notes:
Leaving the action value blank will cause the form to post back to
itself.
I will fix the spacing when I get home, I don't have my editor with me.
The errors should be displayed underneath the container. I made it so that only one error is display at a time, do let me know if you
want to display all the errors at once.
I wouldn't recommend doing the registration form this way, it's way too messy. However, if this is your learning process, then all the power to you.

register.php
<?php
//Connections
try {
$handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
exit($e->getMessage());
}
//Post shit
$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password1 = $_POST['passwordconf'];
$ip = $_SERVER['REMOTE_ADDR'];
$error = null;//set it to null
//Verifcation
if (empty($name) || empty($username) || empty($email) || empty($password) || empty($password1)){
$error .= "Complete all fields\n";
}
// Password match
if ($password != $password1){
$error .= "Passwords don't match\n";
}
// Email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error .= "Enter a valid email\n";
}
// Password length
if (strlen($password) <= 6){
$error .= "Choose a password longer then 6 character\n";
}
if(!isset($error)){
//no error
$sthandler = $handler->prepare("SELECT username FROM users WHERE username = :name");
$sthandler->bindParam(':name', $username);
$sthandler->execute();
if($sthandler->rowCount() > 0){
error .= "exists! cannot insert\n";
} else {
//Securly insert into database
$sql = 'INSERT INTO userinfo (name ,username, email, password, ip) VALUES (:name,:username,:email,:password,:ip)';
$query = $handler->prepare($sql);
$query->execute(array(
':name' => $name,
':username' => $username,
':email' => $email,
':password' => $password,
':ip' => $ip
));
}
}else{
error .= "error occured: ".$error;
}
if(!isset($error)){
header( 'Location: index.php' ) ;
}
else {
header( 'Location: register.php?err='.$error ) ;
}
To display the error on your form place this code:
if(isset($_GET['err'])){
$error = $_GET['err'];
echo "error: $error";
}

Related

Change signup page echo message based on if statement from different page

I am practicing PHP and database creation and would like to change my message based on errors from the input. I can't figure out how to pass the changed messaged back and would appreciate any help given.
This is my sign up page
<main>
<h1>Signup<h1>
<h3>
<?php
echo $errorMsg;
?>
<h3>
<form action="includes/signup.inc.php" method="post">
<input type="text" name="uid" placeholder="Username">
<input type="text" name="mail" placeholder="E-mail">
<input type="password" name="pwd" placeholder="Password">
<input type="password" name="pwd_repeat" placeholder="Repeat Password">
<button type="submit" name="signup-submit">Submit</button>
<form>
</main>
This is my processing page
if(isset($_POST['signup-submit'])){
require 'dbh.inc.php';
$Name = $_POST['uid'];
$Email= $_POST['mail'];
$Password = $_POST['pwd'];
$PasswordRepeat = $_POST['pwd_repeat'];
if(empty($Name) || empty($Email) || empty($Password) || empty($PasswordRepeat)){
header("Location: ../signup.php?error=emptyfields=1"); //Check if any field is empty
exit();
}
else if(!filter_var($Email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $Name)){
header("Location: ../signup.php?error=invalidamil&uid"); //Check if username and email is valid input
exit();
}
else if(!filter_var($Email, FILTER_VALIDATE_EMAIL)){
header("Location: ../signup.php?error=invalidamil&uid=".$Name); //Check if email is valid input
exit();
}
else if($Password !== $PasswordRepeat){
header("Location: ../signup.php?error=passwordCheck&uid=".$Name."&mail=".$Email); // Check if passwords don't match
exit();
}
$sql2 = "SELECT UserName FROM dbo.MainTable WHERE UserName = ?";
$params2 = array($Name, SQLSRV_PARAM_IN);
$stmt2 = sqlsrv_query($conn, $sql2, $params2);
if($stmt2 === false)
{
die(print_r(sqlsrv_errors(), true));
exit();
}
$row_count = sqlsrv_num_rows($stmt2);
if($row_count != 0)
{
$_SESSION['errMsg'] = "Error retrieving username";
header("location: ../register.php");
exit();
}
else if($row_count > 0)
{
$_SESSION['errMsg'] = "Username is already used";
header("Location: ../signup.php?error=UserNameTaken&uid");
exit();
}
else{
$sql = "INSERT INTO dbo.MainTable(UserName,Email,UserPassword)
VALUES (?,?,?)";
$Password = PASSWORD_HASH($_POST['pwd'], PASSWORD_DEFAULT); //Password hashing
$stmt = sqlsrv_query($conn, $sql,array(#$Name,#$Email,#$Password));
if($stmt === false){
die( print_r( sqlsrv_errors(), true));
}else{
$_SESSION['errMsg'] = "Registration completed!";
header("Location: ../signup.php?signup=COMPLETE");
exit();
}
}
I am not sure where to put a change message variable here because I couldn't get it work in the if statements.
You are providing the error message as an url paramenter, so you can access it with php $_GET
<h3>
<?php
echo $_GET['error'];
?>
<h3>

Sign in form not logging in after I enter details

I am creating a login form for a website that should redirect the user to the index page after they log in. The problem I'm having is that when I enter the details for logging in, it runs the error part of the code and I can't seem to figure out where I went wrong. I have gone through my code and even physically compared both the passwords and username and they match. Please help me with where I went wrong.
config.php
<?php
session_start();
$host = 'localhost';
$host_user = 'root';
$host_pass = '';
$db_name = 'the_dms_db';
$conn = mysqli_connect($host, $host_user, $host_pass, $db_name);
if (!$conn) {
echo 'Could not connect to the database';
}
$name = '';
$surname = '';
$username = '';
$email = '';
$errors = array();
if (isset($_POST['register_user'])) {
// receive inputs
$name = mysqli_real_escape_string($conn, $_POST['name']);
$surname = mysqli_real_escape_string($conn, $_POST['surname']);
$username = mysqli_real_escape_string($conn, $_POST['username']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$c_password = mysqli_real_escape_string($conn, $_POST['c_password']);
// form validation that it is filled correctly
if (empty($name)) {
array_push($errors, "Name is required");
}
if (empty($surname)) {
array_push($errors, "Surname is required");
}
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($email)) {
array_push($errors, "Email is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if ($password != $c_password) {
array_push($errors, "Passwords to not match");
}
// check database to see if user exists
$user_check_query = "SELECT * FROM users WHERE username='$username' OR email = '$email' LIMIT 1";
$result = mysqli_query($conn, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) {
if ($user['username'] === $username) {
array_push($errors, 'Username already exists');
}
if ($user['email'] === $email) {
array_push($errors, 'Email already exists');
}
}
// register user if no errors
$pass_hash = password_hash($password, PASSWORD_BCRYPT);
if (count($errors) == 0) {
$query = "INSERT INTO users (name, surname, username, email, password) VALUES ('$name', '$surname', '$username', '$email', '$pass_hash')";
mysqli_query($conn, $query);
$_SESSION['username'] = $username;
$_SESSION['success'] = 'You are now logged in!';
header('location: ./index.php');
}
}
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
if (empty($username)) {
array_push($errors, 'Username is required');
}
if (empty($password)) {
array_push($errors, 'Password is required');
}
if (count($errors) == 0) {
$password = password_hash($password, PASSWORD_BCRYPT);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($conn, $query);
if (mysqli_num_rows($results) == 0) {
$_SESSION['username'] = $username;
$_SESSION['success'] = 'You are now logged in!';
header('location: ./index.php');
} else {
array_push($errors, 'Wrong username/password');
}
}
}
signin.php
<?php
require_once './header.php';
include_once './config.php';
?>
<link rel="stylesheet" href="/assets/css/style.css">
<section class="sign-in-section">
<div class="container">
<div class="form-area ">
<h1>Sign In</h1>
<form action="./signin.php" class="signin-form" method="POST">
<?php include './errors.php'; ?>
<section class="input-sections">
<input type="text" class="inputs form-control" name="username" id="username" placeholder="Username or Email">
<input type="password" class="inputs form-control" name="password" id="password" placeholder="Password">
<button type="submit" class="btn-form btn signin-btn" name="login_user" id="login_user">Sign in</button>
</section>
</form>
Not yet a member? Register here!
</div>
</div>
</section>
signup.php
<?php
include './config.php';
require_once './header.php';
?>
<link rel="stylesheet" href="/assets/css/style.css">
<section class="sign-in-section">
<div class="container">
<div class="form-area ">
<h1>Sign up</h1>
<form action="signup.php" class="signup-form" method="post">
<?php include './errors.php' ?>
<section class="input-sections">
<input type="text" class="inputs form-control" name="name" id="name" placeholder="Name" value="<?php echo $name ?>">
<input type="text" class="inputs form-control" name="surname" id="surname" placeholder="Surname" value="<?php echo $surname ?>">
<input type="text" class="inputs form-control" name="username" id="username" placeholder="Username" value="<?php echo $username ?>">
<input type="text" class="inputs form-control" name="email" id="email" placeholder="Email" value="<?php echo $email ?>">
<input type="password" class="inputs form-control" name="password" id="password" placeholder="Password">
<input type="password" class="inputs form-control" name="c_password" id="c_password" placeholder="Confirm Password">
<button type="submit" class="btn-form btn register-btn" name="register_user" id="register">Register</button>
</section>
</form>
Already have an account? Sing in here!
</div>
</div>
</section>
errors.php
<?php if (count($errors) > 0) : ?>
<div class="error">
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
Shouldn't the returned result have 1 row rather than 0 rows, if it's a match?
Change this
if (mysqli_num_rows($results) == 0)
To this
if (mysqli_num_rows($results) >= 1)
If you ignore the vulnerabilities within the sql statements you should analyse the following to see where you were going astray with the approach above. Using password_hash will generate a new hash on each invocation - so the hashed password will never ( hopefully ) match a newly generated hash. You need to use password_verify instead.
define('BR','<br />');
$password=$_POST['password'];
$query = "SELECT `password` FROM `users` WHERE `username`='$username' LIMIT 1";
$results = mysqli_query( $conn, $query );
$rs=mysqli_fetch_assoc( $results );
if( password_verify( $password, $rs['password'] ) ){
/* OK - The user supplied a good username/password combo */
}else{
/* Bad Foo!!! The supplied password did not verify against the stored hash */
}
If you consider
$pwd='banana';
echo password_hash($pwd,PASSWORD_DEFAULT) . BR;
echo password_hash($pwd,PASSWORD_DEFAULT) . BR;
echo password_hash($pwd,PASSWORD_DEFAULT) . BR;
you will likely see results similar to:
$2y$10$7a4Cvzn51eYa3EJKary8zemJn4/GiFA.2fqYQrwd6QrRORIk552Wm
$2y$10$E5.28SSkQo2lZv11zilkBO1L35umAFzr5Zr2yKScX4nDgFkN.kTbK
$2y$10$HEzHOFT/7V972XDEB9uzRuU/dxHxRnSXs64wu1qdahJs2CSp3wwD6
As you can see they are all different...

How to display validation errors in my website?

I just want this PHP code to display form validation errors in my website whenever someone uses the form incorrectly. Here is the code and I will also include the HTML of the form.
The code is only for reference, if you have a better way of doing it, then please show me.
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$number = mysqli_real_escape_string($conn, $_POST['number']);
$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
// Error handlers
// Check for empty fields
if (empty($first) || empty($last) || empty($email) || empty($number) || empty($uid) || empty($pwd)) {
header("Location: ../signup.php?signup=empty");
exit();
} else {
// Check if input characters are valid
if (!preg_match("/^[a-zA-Z'-]+$/",$first) || !preg_match("/^[a-zA-Z'-]+$/",$last)) {
header("Location: ../signup.php?signup=invalid");
exit();
} else {
// Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?signup=invalidemail");
exit();
} else {
if (preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $number)) {
header("Location: ../signup.php?signup=invalidnumber");
exit();
} else {
$sql = "SELECT * FROM users WHERE user_uid='$uid'";
$result = mysqli_query($conn, $sql);
$resultcheck = mysqli_num_rows($result);
if ($resultcheck > 0) {
header("Location: ../signup.php?signup=usertaken");
exit();
} else {
// Hashing the password
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
// Insert the user into the database
$sql = "INSERT INTO users (user_first, user_last, user_email, user_number, user_uid, user_pwd) VALUES ('$first', '$last', '$email', '$number', '$uid', '$hashedPwd');";
mysqli_query($conn, $sql);
header("Location: ../accountcreated.php");
exit();
}
}
}
}
} else {
header("Location: ../signup.php");
exit();
}
Here is the HTML code:
<form class="memberform" action="includes/signup.inc.php" method="POST" novalidate>
<input id="spfirst" class="form_fname" type="text" name="first" placeholder="First Name">
<span class="error_form"></span>
<input id="splast" class="form_lname" type="text" name="last" placeholder="Last Name">
<span class="error_form"></span>
<input class="form_email" type="email" name="email" placeholder="E-mail">
<span class="error_form"></span>
<input id="spnumber" class="form_tel" type="tel" name="number" placeholder="Phone number">
<span class="error_form"></span>
<input id="spuser" class="form_user" type="text" name="uid" placeholder="Username">
<span class="error_form"></span>
<input class="form_password" type="password" name="pwd" placeholder="Password">
<span class="error_form"></span>
<button type="submit" name="submit">Create Account</button>
</form>
Okay there it is. I already tried so many things a nothing seems to work... Maybe it's due to my limited knowledge with PHP.
This is not the best way to do it in my opinion, but following your current code, I suggest you do this.
In your signup.php file, add this where you want the error message to appear (within the HTML if you want):
<?php
if(isset($_GET['signup'])){
switch($_GET['signup']){
case 'empty':
$msg = 'Empty fields';
break;
case 'invalid':
$msg = 'Invalid input';
break;
case 'invalidemail':
$msg = 'Invalid email';
break;
case 'invalidnumber':
$msg = 'Invalid number';
break;
case 'usertaken':
$msg = 'User taken';
break;
default:
$msg = ''; // Default message, if any
break;
}
echo '<div class="error_div">'.$msg.'</div>'; // here's where the message appears
}
?>
That will show your messages. Obviously, feel free to change the class name and style it as you wish.
Or you can simply do something like this (changing the text and stuff depending on the result you're looking for):
<?php
if(isset($_GET['signup'])){
if($_GET['signup'] == 'empty'){
echo '<span class="error_form">Empty values</span>';
}
}
?>
Since you're redirecting users to the signup page with a specific error message (Example: usertaken), you can use $_GET to handle the errors.
So in your signup page, do this
$error should = "" ;
if(isset($_GET['signup'])) {
$error = $_GET['signup'];
if(!empty($error){
//check for specific errors
if($error == "usertaken"){
$errorMsg = "The username has already been taken, try again";
}
}
}
You can use the $errorMsg in your HTML and put it where you want to display the error and design it accordingly.
NOTE: I have not done any sanitization, trying to keep this short.

Resetting password after submit doesn't change password

I am trying to reset password but after I submit new password it takes me back to login without changing it. I think this happens because it doesn't remember the email and token. It shows me the form but after I click submit doesn't do anything.
Code:
<?php
if (isset($_GET['email']) && isset($_GET['token'])) {
include('databaze.php');
$conn = new mysqli($servername, $username, $password, $dbname);
$email = $conn->real_escape_string($_GET['email']);
$token = $conn->real_escape_string($_GET['token']);
$data = $conn->query("SELECT did FROM tbldoc WHERE email='$email' AND
token='$token'");
if ($data->num_rows > 0) {
include('reset-form.php');
if (isset($_POST['resetPass'])) {
$password = $_POST["password"];
$password_conf = $_POST['password-conf'];
$email = $_POST["email"];
$token = $_POST["token"];
if (empty($password) || empty($password_conf)) {
echo "<br><br>Fill the form";
} elseif ($password !== $password_conf) {
echo "<br><br>Password doesn't match Password Confirmation";
}
$password = md5($password);
$conn->query("UPDATE tbldoc SET hashedpwd='$password', token='' WHERE email='$email'");
}
} else {
echo "Please check your link!";
}
} else {
header("Location: login.php");
exit();
}
?>
form:
<form method="post" action="resetpassword.php" class="form-signin">
<h2 class="form-signin-heading">Reset Password</h2>
Password <input type="password" class="form-control" name="password" placeholder="Password">
<br>
Password Confirmation <input type="password" class="form-control" name="password-conf"
placeholder="Password Confirmation">
<br>
<input type="hidden" class="form-control" name="email" value="<?php echo $email;?>">
<input type="hidden" class="form-control" name="token" value="<?php echo $token;?>">
<input type="submit" class="btn btn-lg btn-primary btn-block" name="resetPass" value="Reset your Password">
Could you help me?
Your form is type POST and you are expecting GET
isset($_POST['email']) && isset($_POST['token'])
Could be?
May be because of this line, your SQL is not able to search email
$email = $conn->real_escape_string($_GET['email']);
Add this to your form. It will remember the email and token:
<input type="hidden" name="email" value="<?php echo #$email; ?>">
<input type="hidden" name="token" value="<?php echo #$token; ?>">
Your form method is POST and you are checking the data in GET. So every time else part will be called. change this line in your code
if (isset($_GET['email']) && isset($_GET['token'])) {
with
if (isset($_POST['email']) && isset($_POST['token'])) {
Your form action is post method so you need to check the condition as
if (isset($_POST['email']) && isset($_POST['token']))
This is full code. you use some place GET and some place POST method so it will work for POST method...
<?php
if (isset($_POST['email']) && isset($_POST['token'])) {
include('databaze.php');
$conn = new mysqli($servername, $username, $password, $dbname);
$email = $conn->real_escape_string($_POST['email']);
$token = $conn->real_escape_string($_POST['token']);
$data = $conn->query("SELECT did FROM tbldoc WHERE email='$email' AND
token='$token'");
if ($data->num_rows > 0) {
include('reset-form.php');
if (isset($_POST['resetPass'])) {
$password = $_POST["password"];
$password_conf = $_POST['password-conf'];
$email = $_POST["email"];
$token = $_POST["token"];
if (empty($password) || empty($password_conf)) {
echo "<br><br>Fill the form";
} elseif ($password !== $password_conf) {
echo "<br><br>Password doesn't match Password Confirmation";
}
$password = md5($password);
$conn->query("UPDATE tbldoc SET hashedpwd='$password', token='' WHERE email='$email'");
}
} else {
echo "Please check your link!";
}
} else {
header("Location: login.php");
exit();
}
?>
or change your form like <form method="GET" action="resetpassword.php" class="form-signin">

how to implement token base form submission in php

i have been trying to create my own OOPs style register login system in php, i have implemented some security features like xss protection using htmlentites(), prepare method for SQLinjection protection and token based form submission for csrf protection(currently i am stuck implementing this functions in my code, getting "Invalid token" while submitting form data).
But I am not very sure it is good enough for secure site to produce for real live project or not. And i would like you to review my codes, Please help me to solve implementing token base form submission in my code and suggest me the way to improve my coding style in my current code.
This is my register.php page
<?php
//error_reporting(0);
session_start();
if(isset($_POST["submit"])){
include "Db_handlers.php";
$db = new DbHandler();
$res = $db->createUser($_POST["name"], $_POST["email"], $_POST["password"], $_POST["re-password"], $_POST['token']);
print_r($res);
/*if($res){
echo "test";
}
else {
echo $res;
}*/
}
$token = $_SESSION['token'] = md5(uniqid(mt_rand(),true));
?>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<div class="field">
<label for="name">Name:</label>
<input type="text" name="name" value="" />
</div>
<div class="field">
<label for="email">Email:</label>
<input type="text" name="email" value="" />
</div>
<div class="field">
<label for="password">Password:</label>
<input type="password" name="password" value="" />
</div>
<div class="field">
<label for="repassword">Re-Password:</label>
<input type="password" name="re-password" value="" />
</div>
<input type="hidden" name="token" value="<?=$token;?>"/>
<input type="submit" name="submit" value="submit" />
</form>
This is my DB handler class
<?php
require 'functions.php';
class DbHandler {
private $conn;
public function __construct() {
try{
$this->conn = new PDO("mysql:host=127.0.0.1;dbname=task_manager", "root" , "");
// echo "Connected";
}
catch(PDOException $e){
//die($e->getMessage());
echo "Connection Failed: ".$e->getMessage();
}
}
public function createUser($name, $email, $password, $repassword, $utoken) {
// $error = array();
$error = '';
$required_fields = array($name, $email, $password, $repassword);
$fields = array_map('trim', $required_fields);
if (in_array(null, $fields)) {
$error = 'Fields marked with an asterisk are required';
}
else if($this->valid_token($utoken) == false){
$error = "Invalid Token...!!!";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error = 'Please enter a valid email address !';
}
else if(strlen($password) < 6){
$error = "Password must be atleast 6 characters";
}
else if($password !== $repassword){
$error = "Password do n\' t match!!";
}
else{
$name = escape($name);
$email = escape($email);
$password_hash = escape($password);
// First check if user already existed in db
if (!$this->isUserExists($email)) {
// Generating password hash
$password_hash = password_hash($password, PASSWORD_DEFAULT, ['cost'=>12]);
// insert query
$stmt = $this->conn->prepare("INSERT INTO users(name, email, password_hash, status) values(:name, :email, :password_hash, 1)");
//$stmt->bind_param("ssss", $name, $email, $password_hash);
$result = $stmt->execute(array(':name' => $name,':email' => $email,':password_hash' => $password_hash));;
//$stmt->close();
// Check for successful insertion
if ($result) {
// User successfully inserted
return $result;
} else {
// Failed to create user
$error = "Failed to create user";
}
} else {
// User with same email already existed in the db
$error = "User already exists";
}
}
return $error;
}
private function isUserExists($email) {
$stmt = $this->conn->prepare("SELECT id from users WHERE email = :email");
//$stmt->bind_param("s", $email);
$stmt->execute(array(':email' => $email));
//$stmt->bind_result();
$num_rows = $stmt->rowCount();
//$stmt->close();
return $num_rows > 0;
}
public function valid_token($token){
if(!isset($_SESSION['token']) || $token != $_SESSION['token'])
return false;
}
}
Your code is really hard to read... You should indent it properly.
Back to your question. It seems, you just return false, if your token is incorrect, but your forget to return true, if it is correct. If your return nothing, you implicitly return null, which evaluates to false. I guess, your code works, if your change valid_token like this:
public function valid_token($token){
return isset($_SESSION['token']) && $token == $_SESSION['token'];
}

Categories