PHP Form Validation Showing Errors Before Submission - php

I am working on making a PHP and MySQL application for practicing my new-found love for programming. I have a login script; the HTML form is as follows:
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
Username:
<input type="text" name="username" maxlength="60"><br />
Password:
<input type="password" name="password" maxlength="60"><br />
Confirm Password:
<input type="password" name="password_confirm" maxlength="60"><br />
<input type="submit" name="submit" value="Register"><br />
</form>
This continues into the PHP form validator:
<?php
$username_original = $_POST["username"];
$password_original = $_POST["password"];
$password_confirm_original = $_POST["password_confirm"];
//This makes sure they did not leave any fields blank
function FieldComplete($user, $password, $password_confirm) {
if (!isset($user, $password, $password_confirm) &&
$user && $password && $password_confirm == "" || " ") {
$field_confirm = false;
} else {
$field_confirm = true;
}
if ($field_confirm == true) {
echo "";
} else {
echo "You did not complete all the required fields.";
}
}
FieldComplete($username_original, $password_original, $password_confirm_original);
?>
I realize that making a function for this might seem a little useless, but it was as close as I got to the result I wanted.
However, this code displays the error "You did not complete all the required fields." on loading of the page. I only want that error to display if they have pressed the register button and still have a blank field.
Any advice or help is greatly appreciated. Thanks StackOverflow community!

If you want to run the php code only if button is submitted so you need to check about that at the top of your page
if(isset($_POST["submit"]))
{
//form has been submitted
//do validation and database operation and whatever you need
} else {
//form has not been submitted
//print the form
}

In addition to Fabio answer, you can improve your code like this:
if(isset($_POST['submit'])){
$username_original = $_POST["username"];
$password_original = $_POST["password"];
$password_confirm_original = $_POST["password_confirm"];
$isComplete = FieldComplete($username_original, $password_original, $password_confirm_original);
if(!$isComplete){
echo "You did not complete all the required fields.";
}
}else{
//display the form
}
function FieldComplete($user, $password, $password_confirm) {
if (!isset($user, $password, $password_confirm) &&
$user && $password && $password_confirm == "" || " ") {
return false;
} else {
return true;
}
}

Related

PHP form to insert into database, check for nothing entered

My question is, how do I get the form to display an error when the user doesn't input a field into the form. I can get it to work when they don't fill out the form at all and just hit enter, but cannot get it to work if they only fill out a few fields. They could fill out the title field and the run time field and will be able to submit it. How can I get it to make sure that every field is filled out?
<?php
$databaseName = 'movie_database';
$databaseUser = 'root';
$databasePassword = 'root';
$databaseHost = '127.0.0.1';
$conn = new mysqli($databaseHost, $databaseUser, $databasePassword, $databaseName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
if(isset($_POST['submit'])) {
$value = mysqli_real_escape_string($conn,$_POST['title']);
$value2 = mysqli_real_escape_string($conn,$_POST['rating']);
$value3 = mysqli_real_escape_string($conn,(int)$_POST['Runtime']);
$value4 = mysqli_real_escape_string($conn,(float)$_POST['movie_rating']);
$value5 = mysqli_real_escape_string($conn,$_POST['release_date']);
// Checks for empty fields
if (empty($value) && empty($value2) && empty($value3) && empty($value4) && empty($value5)) {
echo 'Please correct the fields';
return false;
}
// Concatenate the $values into the string
$sql = "INSERT INTO movies(title,rating,Runtime,movie_rating,release_date)
VALUES('$value','$value2','$value3','$value4','$value5')";
if ($conn->query($sql)) {
$msg = "New record created successfully";
} else {
$msg = "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
<form method="post"/>
<p>Enter Movie Title: <input type="text" name="title"/></p>
<p>Enter Movie Rating(G,PG,PG-13,R): <input type="text" name="rating"/></p>
<p>Enter Movie Runtime in minutes: <input type="text" name="Runtime"/></p>
<p>Enter IMDB Movie Rating(0-10.0): <input type="text" name="movie_rating"/></p>
<p>Enter Movie Release date(YYYY-MM-DD): <input type="text" name="release_date"/></p>
<button type="submit" name="submit">Submit</button
</form>
<?php
if (isset($msg)) {
echo $msg;
}
?>
From Front side you can add required attribute to each input. So add it in every input field like :
<input type="text" name="title" required/>
From back-end side (using PHP) If you want all value must be fill up then change && with || in your condition
// Checks for empty fields
if (empty($value) || empty($value2) || empty($value3) || empty($value4) || empty($value5)) {
echo 'Please correct the fields';
return false;
}
if (empty($value) && empty($value2) && empty($value3) && empty($value4) && empty($value5)) {
echo 'Please correct the fields';
return false;
}
This should be 'or'

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 validate a form in PHP, then redirect to an external page

I'm trying to validate a registration form using HTML and PHP, and insert the data into an SQL database. Upon registration, I'd like for my user to be directed to their personal dashboard. I can get everything to work except for the redirect upon form submission.
Here is the PHP at the start of the page:
<?php
// define variables and set to empty values
$emailErr = $passErr = $confirmErr = $email = $pass = $confirm = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["pass"])) {
$passErr = "You must have a password";
} else {
$pass = test_input($_POST["pass"]);
}
if (empty($_POST["confirm"])) {
$confirmErr = "You must confirm your password";
} else {
$confirm = test_input($_POST["confirm"]);
}
if ($pass != $confirm) {
$confirmErr = "Your passwords must match";
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = test_input($_POST["email"]);
$pass = test_input($_POST["pass"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
And my HTML form:
<div class="container">
<form class="form-signin" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<h2 class="form-signin-heading">Register below:</h2>
<span class="error"><?php echo $emailErr;?></span>
<input type='email' class="form-control" placeholder="enter email..." name='email'/>
<span class="error"><?php echo $passErr;?></span>
<input type='password' class="form-control" placeholder="enter password" name='pass'/><span class="error"><?php echo $confirmErr;?></span>
<input type='password' class="form-control" placeholder="confirm password" name='confirm'/>
<input type='submit' class="btn btn-success btn-block" name="submit" value="submit">
<h5>Already have an account? Log in.</h5>
</form>
</div>
Note the use of
<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
on
<form action="">
param. Using this function I can't get a redirect.
I've included my SQL entries following the HTML, and the entries are working just fine, but the header(); tag doesn't seem to work. See here:
<?php
$email = $_POST['email'];
$pass = md5($_POST['pass']);
// Database connection
require 'database.php';
$sql = "SELECT email FROM users WHERE email = '".$email."'";
$result = $conn->query($sql);
$row_count = $result->num_rows;
if ($row_count == 1) {
// user already exists
header('Location: login.php');
} elseif ($row_count > 1) {
// just to double check multiple entries aren't input into the DB
echo 'There are too many records with that name!';
} else {
// enter user into DB
$sql = "INSERT INTO users (email, pass)
VALUES ('".$email."', '".$pass."')";
if ($conn->query($sql) === TRUE) {
header('Location: dashboard.php');
exit();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
}
?>
Any ideas what I'm doing wrong?
hi i have seen you code in your code you are using login.php for redirecting from header tag.
and in html file you are using login.html file for checking account is exists or not.
Please check file extension for your login file.
you can use following link for header function details:
PHP header(Location: ...): Force URL change in address bar
If I understand it right, what you can do is redirect back to your page with the link :
<form name="form-lignin" method="post" action="this-php-page.php">
On the same page you can then create a section that will show up only if the form has been submitted and the form will be hidden. The section can be personalised for each user then as well.
You can do this by adding a hidden field to your form.
<input type='hidden' name='submission' value="something"/>
Then you can add this php :
if ($_POST["submission"]=="something") {
*Dashboard content?*
} else {
*The actual form...*
}
Hope this helped :)
1.you need ensure the code has run
if ($conn->query($sql) === TRUE) {
echo 'is run!';exit;
header('Location: dashboard.php');
exit();
}
and you can use if ($conn->query($sql)) instand if ($conn->query($sql) === TRUE)
2.notice ,if the "exit;" code run ,"mysqli_close($conn);" will useless。
You first need to put all your php code above the html so that the html output will be sent to the browser after execution of the validation script.
Then
1 Capture form values
2 Validate form values
3 If Every thing is ok. Then sanitize the input and insert it into the database.
4 if insert successful, Redirect it to another page, Using header('location:http://example.com');
Thats it

Need advice / guidance on makin registration form

<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color:red;}
</style>
</head>
<body>
<?php
$username = $password = $email = "";
$usernameerr = $passworderr = $emailerr = "";
if ($_SERVER["REQUEST_METHOD"]=="POST") {
if (empty($_POST["username"])) {
$usernameerr = "Please fill username";
} else {
$username = test_input($_POST["username"]);
if(!preg_match("/^[a-zA-Z]*$/",$username)) {
$usernameerr = "Only letters allowed";
}
}
if (empty($_POST["email"])) {
$emailerr = "Please fill e-mail";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$emailerr = "not a valid e-mail";
}
}
if (empty($_POST["password"])) {
$passworderr = "Cannot be blank";
} else {
$password = test_input($_POST["password"]);
if(!preg_match("/^[a-zA-Z]*$/",$password)) {
$pasworderr = "Must be Letters";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$con = mysqli_connect('localhost','root','','my_db');
if (mysqli_connect_errno()) {
echo "Fail to connect :".mysqli_connect_error();
}
$username = mysqli_real_escape_string($con, $_POST["username"]);
$password = mysqli_real_escape_string($con, $_POST["password"]);
$email = mysqli_real_escape_string($con, $_POST["email"]);
$sql = "INSERT INTO register(Username, Password, Email)
VALUES ('$username','$password','$email')";
if (!mysqli_query($con,$sql)) {
die ('Error: '.mysqli_error($con));
}
echo "Registration successful";
mysqli_close($con);
?>
<h2>Register</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Username :<input type="text" name="username" value="<?php echo $username;?>">
<span class="error">*<?php echo $usernameerr;?></span>
<br><br>
Password :<input type="text" name="password" value="<?php echo $password;?>">
<span class="error">*<?php echo $passworderr;?></span>
<br><br>
E-mail :<input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailerr;?></span>
<br><br>
<input type="submit" value="submit" name="submit">
</form>
</body>
</html>
Hi, I am a newbie, and I need advice on making registration form. So here is the code for my registration form, the validation code works and it submit data to mysql database too. But, the problem is, it will submit data to database every time it loads (even if it is blank). What line of codes should I add to prevent the form submitting data when it is not filled completely / filled with the right format.
Thx in advance.
You have to check if there's any data in the fields.
Just add this line before your sql executes, after $email = mysqli_real_escape_string($con, $_POST["email"]); :
if ($username != "" && $password != "" && $email != "")
{
//your sql and rest of the script goes here
}
else
{
//don't save the data if it's not completed well
//do whatever you want in that case no valid data was completed
}
Notes: I answered only to your question but be careful, you have some implementation mistakes. You should just use a flag that by default is 1 and, if an error is found in any of your validation functions, the falg should be set to 0 and you should check the value of the flag before the sql instead of checking the content of the $_POST variables again.
Edit: BETTER SOLUTION FOR YOUR CODE
Add this block before the sql:
if ($usernameerr == "" && $passworderr == "" && $emailerr == "")
{
//no errors, all fine we can add to the database
}
else
{
//we have errors, do something but don't add the data
}
Please outsource your DB-Connection and your DB-Insert in some seperate files and speak to them per ajax-request..
your db-insert-query should be taken place after you validation and at the end of the
if ($_SERVER["REQUEST_METHOD"]=="POST") {
block
You did not close the $_SERVER["REQUEST_METHOD"]=="POST" block properly.
Also inside the if ($_SERVER["REQUEST_METHOD"]=="POST") { block you can add another
if condition as if(!empty($_POST["username"] && !empty($_POST["email"] && !empty($_POST["password"]) {....}

login form needs to be completed a number of times before it logs in

I have a login form (HTML -> PHP). I enter the correct details, it then reloads the page and i have to enter the details again. I press submit and then it does it again. On the third time (sometimes the second I think) it actually logs me in.
Any help would be greatly appreciated.
Here is the forms HTML:
<!-- Login Form -->
<form method="post" id="login-form-splash">
<input type="text" class="text" name="username" onfocus="if(this.value == 'Username') { this.value = ''; }" value="Username" />
<input type="password" name="password" class="password" onfocus="if(this.value == 'Password') { this.value = ''; }" value="Password" />
<input type="submit" name="submit" value="Login" class="submit" />
<br />
<span>Lost Password?</span>
<br />
No account yet? Register.<br />
</form>
And here is the PHP actually doing the login:
<?php
//Check if login form was submitted.
if(isset($_POST['submit']))
{
//include important settings and functions.
include($_SERVER['DOCUMENT_ROOT'] . '/includes/config.php');
//Check if both fields were completed.
if($_POST['username'] == '' || $_POST['password'] == '')
{
//Tell them whats wrong.
echo "<script language=\"javascript\">alert('You need to complete both fields.');</script>";
} else
{
//The completed both fields.
//Localise vars.
$username = $_POST['username'];
$password = $_POST['password'];
//Protect against SQL Injection using mysql_prep function. [mysql_prep can be found in ./includes/functions.php]
mysql_prep($username);
mysql_prep($password);
//MD5 Hash the password to check against hashed password in DB.
$password = md5($password);
//Connect to MySQL Database.
include($_SERVER['DOCUMENT_ROOT'] . '/includes/connect.php');
//If connection exists
if(isset($mysql_connection))
{
//Run MySQL Query on DB.
$sql = "SELECT * FROM `users` WHERE `username` = '$username' AND `password` = '$password'";
$result = mysql_query($sql, $mysql_connection) or die('Cannot Execute:'. mysql_error());
//Check if there is a match. There can only be one.
if(mysql_num_rows($result) == 1)
{
//Create session variables and set values within them.
$_SESSION['username'] = $username;
//Redirect to Members page.
header('Location: members.php');
} else
{
//Username and Password are not correct, or the account doesn't exist.
echo "<script language=\"javascript\">alert('Please check that you have entered the details correctly.');</script>";
}
} else
{
//Database error.
echo "<script language=\"javascript\">alert('There was a database error. Please try again or contact a technician at errors#eatgamesleep.com');</script>";
}
}
}
?>
Maybe you should replace
if(isset($mysql_connection)) {
to just
if($mysql_connection){

Categories