I'm trying to get some form validations to work, but my script registers a user even if the data is incorrect and doesn't validate.
Also, what should I write so it can check whether the user is already in the database and return an error if so?
For example, if I just typed "aaaa" in all text boxes, it would register the user. What should happen if a user entered incorrect data (wrong format) is an error message should appear, and it should not register until the user enters correct data. But it registers the user no matter what I enter, as if there were no validations written.
<?php
include "db.php";
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $passwordErr = $cpasswordErr = "";
$cpassword = "";
$cust_email = $cust_username = $cust_password = $cust_fullname = $cust_country = $cust_dob = $cust_gender = $cust_phone = "";
if (isset($_POST["btnsignup"])) {
//Username Validation
if (empty($_POST["txtcust_username"])) {
$nameErr = "Name is required";
} else {
$cust_username = test_input($_POST["txtcust_username"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z0-9]*$/", $cust_username)) {
$nameErr = "Only letters, numbers are allowed and no white space allowed";
}
}
//Email Validation
if (empty($_POST["txtcust_email"])) {
$emailErr = "Email is required";
} else {
$cust_email = test_input($_POST["txtcust_email"]);
// check if e-mail address is well-formed
if (!filter_var($cust_email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
//Password Validation
if (!empty($_POST["txtcust_password"]) && ($_POST["txtcust_password"] == $_POST["txtcust_cpassword"])) {
$cust_password = test_input($_POST["txtcust_password"]);
$cust_cpassword = test_input($_POST["txtcust_cpassword"]);
if (strlen($_POST["txtcust_password"]) <= '6') {
$passwordErr = "Your Password Must Contain At Least 6 Characters!";
} elseif (!preg_match("#[0-9]+#", $cust_password)) {
$passwordErr = "Your Password Must Contain At Least 1 Number!";
} elseif (!preg_match("#[A-Z]+#", $cust_password)) {
$passwordErr = "Your Password Must Contain At Least 1 Capital Letter!";
} elseif (!preg_match("#[a-z]+#", $cust_password)) {
$passwordErr = "Your Password Must Contain At Least 1 Lowercase Letter!";
}
} elseif (!empty($_POST["txtcust_password"])) {
$cpasswordErr = "Please Check You've Entered Or Confirmed Your Password!";
}
$cust_fullname = $_POST['txtcust_fullname'];
$cust_country = $_POST['txtcust_country'];
$cust_dob = $_POST['txtcust_dob'];
$cust_gender = $_POST['txtcust_gender'];
$cust_phone = $_POST['txtcust_phone'];
//Insert Into Table
$insert = "INSERT INTO customer (cust_email,cust_username,cust_password,cust_fullname,cust_country,cust_dob,cust_gender,cust_phone)
VALUES ('$cust_email','$cust_username','$cust_password','$cust_fullname','$cust_country','$cust_dob','$cust_gender','$cust_phone') ";
$run = mysqli_query($conn, $insert);
if ($run) {
setcookie("Name", $cust_username);
header("Location: home.php");
} else
echo "User has not been Add";
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
TL;DR You do a bunch of validation and set a bunch of error messages, but then ignore all of that and run the INSERT no matter what. Add an if/else statement to handle validation errors or do the insert.
Let's break this down. Your code isn't really a Minimal, Complete, and Verifiable Example, but we can make it into one. Stripping out all the unnecessary stuff, your code is basically this:
<?php
include "db.php";
// initializing some variables
// ...
// a bunch of validation stuff, where you set
// variables like $nameErr and $emailErr
// ...
// logic where you initialize $cust_fullname, $cust_country, etc.
// ...
/***************************************************************
* The database insertion, without ever checking whether
* the data validated!
***************************************************************/
//Insert Into Table
$insert = "INSERT INTO customer (cust_email,cust_username,cust_password,cust_fullname,cust_country,cust_dob,cust_gender,cust_phone)
VALUES ('$cust_email','$cust_username','$cust_password','$cust_fullname','$cust_country','$cust_dob','$cust_gender','$cust_phone') ";
$run = mysqli_query($conn,$insert);
// more code not relevant here...
?>
So, you just run the INSERT, regardless of what happens in the validation stage. There's your problem.
As for your second question (how to check for an existing user), that's a little broad for this site, and you generally should only ask one question at a time. Please try something first, then post that as a second question if you get stuck.
Related
I'm looking to create a sign-up page for a large-scale website which means I'm using a lot more layers of validation then I would normally do, given this should be common practice but in this particular case more than any other situation it is imperative.
I've already written most of the code required and formatted it in an order which I believed wouldn't lead to any undefined variable errors, however, upon form submission it doesn't create a new SQL row and doesn't return any errors under the error handling areas of the form validation. In all fairness, the error handling is quite simple at this point and is not a final version, just what I put in place to help me debug and troubleshoot any issues which should arise.
Here's the PHP code, and the snippet of the piss-poor error handling that is supposed to output an error message if an error occurs, to re-state, this error handling isn't final.
$conn = mysqli_connect('localhost', 'root2', '123', 'db');
$signupConditionsMet = "0";
if (isset($_POST["email"]) && isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["passwordCheck"]) && isset($_POST["birthdate"])) {
$signupConditionsMet = "1";
$birthGood = true;
$passGood = false;
$nameGood = false;
$emailGood = false;
}
$usernameSearch = $conn->prepare("SELECT * FROM users WHERE username = ?");
$userInsertion = $conn->prepare("INSERT INTO users (username, passwd, birthdate, email) VALUES (?,?,?,?)");
$nameErr = $emailErr = $passErr = $birthErr = "";
$name = $email = $pass = $birth = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["username"];
$email = $_POST["email"];
$pass = $_POST["password"];
$birthdate = $_POST["birthdate"];
$passCheck = $_POST["passwordCheck"];
}
if ($signupConditionsMet === "1"){
function test_input($name) {
if (!preg_match("/^[a-z\d_]{2,15}$/i",$name)) {
$nameErr = "Only letters and white space allowed";
} else {
$nameGood = true;
return $name;
echo "did name ez";
}
}
function test_input2($email){
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
} else {
$emailGood = true;
return $email;
echo "did email ez";
}
}
function test_input3($password){
if (!preg_match("/^[a-z\d_]{2,15}$/",$pass)) {
$passErr = "Invalid password format";
} else if (!preg_match("/^[a-z\d_]{2,15}$/",$passCheck)){
$passErr = "Invalid password check format";
} else if ($_POST["password"] !== $_POST["passwordCheck"]){
$passErr = "Passwords do not match";
} else {
$passwd2 = AES_ENCRYPT($_POST["password"], 'mysecretstring');
$passwdGood = true;
return $passwd2;
echo "did pass ez";
}
}
}
if (($signupConditionsMet === "1") && ($birthGood === true) && ($nameGood === true) && ($passwdGood === true) && ($emailGood === true)) {
if ($usernameSearch->execute(array($_POST['username']))) {
while ($row = $usernameSearch->fetch()) {
if (!empty($row['id'])) {
$creationError = "This username is already taken";
} else {
$userInsertion->bindParam(1, $name);
$userInsertion->bindParam(2, $passwd2);
$userInsertion->bindParam(3, $birthdate);
$userInsertion->bindParam(4, $email);
$userInsertion->execute();
header('Location: userlanding.php');
}
}
}
}
/* PHP inside the HTML to output errors */
<?php if ($signupConditionsMet === "1") { echo "all inputs received"; echo $_SERVER["REQUEST_METHOD"];} else { echo "drats, they weren't all there"; echo $name; echo $email; echo $birthdate; echo $pass; echo $passCheck;}?>
<?php if ($passErr) { echo $passErr;} else if ($nameErr) { echo $nameErr;} else if ($emailErr) { echo $emailErr;} else if ($birthErr) { echo $birthErr;} ?>
Disregarding the previously admitted terrible error handling, I can't seem to wrap my head around why it doesn't work in its current form. It returns (from the client-side reporting) that all inputs were received and there isn't any fatal errors thrown from running the PHP code. In addition, the second client-side code which prints any errors doesn't print anything either, implying that all functions operated correctly, however, the echos at the bottom of the input tests don't echo the strings they've been assigned, implying those didn't work, but there was no errors. Hmm. Perhaps I'm missing something blatantly obvious regarding my syntax but I don't see why it wouldn't work. Any help would be appreciated.
I thought of using php header to redirect upon validation successful. However it's seems broken to me. How do I implement one then. Condition is when all the validation is validated then it would only redirect.
<?php
// define variables and set to empty values
$nameErr = $lastnameErr = $emailErr = $passwordErr = $confirmpasswordErr = $checkboxErr= "";
$name = $lastname = $email = $password = $confirmpassword = $checkbox = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$nameErr = "First Name is required";
}else {
$name = test_input($_POST["firstname"]);
}
if (empty($_POST["lastname"])) {
$lastnameErr = "Last Name is required";
}else {
$name = test_input($_POST["lastname"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
}else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if(!empty($_POST["password"]) && ($_POST["password"] == $_POST["confirmpassword"])) {
$password = test_input($_POST["password"]);
$confirmpassword = test_input($_POST["confirmpassword"]);
if (strlen($_POST["password"]) <= '8') {
$passwordErr = "Your Password Must Contain At Least 8 Characters!";
}
elseif(!preg_match("#[0-9]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Number!";
}
elseif(!preg_match("#[A-Z]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Capital Letter!";
}
elseif(!preg_match("#[a-z]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Lowercase Letter!";
}
}
elseif(empty($_POST["password"])) {
$passwordErr = "Password not filled at all";
}
elseif(!empty($_POST["password"])) {
$confirmpasswordErr = "Password do not match";
}
if(!isset($_POST['checkbox'])){
$checkboxErr = "Please check the checkbox";
}
else {
$checkbox = test_input($_POST["checkbox"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
header('Location: http://www.example.com/');
Set $error = 1 if any condition get failed , and at the bottom check if($error!=1) then redirect
and you can also use javascript redirect if header is not working
Look at the closing "?>"-Tab. header will generate a html-header, but is a php-function and should be inside the ?php ?> bracket.
Consider using html5 input validation - saves some code and server roundtrips to let the browser do the validation
Omit the closing "?>" altogether. Its not necessary and can lead to hard to see errors when there is content - even blanks - after the "?>"
Consider using the filter_input function with appropriate parameters to access $_POST and set your variables.
I currently have a form that checks if the username and password exist and logs you and redirects you to the homepage. However if you leave the email and password section blank, you also are able to log into the site. I'm looking to add some sort of validation to avoid someone from just using empty input variables.
This is what I have...
<?php
session_start();
include_once 'config.php';
$email ="";
$userpassword ="";
$errors = 0;
$emailError ="";
$passwordError ="";
if(isset($_SESSION['user'])!="")
{
header("Location: home.php");
}
if(isset($_POST['loginBtn']))
{
if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
{
$emailError = "Email is not valid";
$errors = 1;
}
if(!empty($_POST["password"])) {
$passwordError = "Please enter a Password";
$errors = 1;
}
$email = mysql_real_escape_string($_POST['email']);
$userpassword = mysql_real_escape_string($_POST['password']);
$result=mysql_query("SELECT * FROM users WHERE emailAddress='$email'");
$row=mysql_fetch_array($result);
if($row['password']==md5($userpassword))
{
$_SESSION['user'] = $row['user_id'];
header("Location: home.php");
}
else
{
?>
<script>alert('First time visitors, please create an account to play'); </script>
<?php
}
}
?>
Client Side validation such as JavaScript and HTML5 can be turned off or directly edited via the browser. Always use server side validation as the final authority.
Also, When checking login credentials you need to do a combination check in the where clause.
WHERE username ='$u_user' AND password = '$u_pass'
This is especially the case when allowing the reuse of controlling columns (username, email). Passwords are not always unique.
In the OP's case the lookup on the email only could return multiple results.
<?php
session_start();
include_once('config.php');
IF (isset($_SESSION['user'])!="") { header("Location: home.php"); }
IF (isset($_POST['loginBtn'])) { // the form was submitted
$err = ""; // default error as empty
$email= trim($_POST['email']);
$password = trim($_POST['password']);
// validation
IF (empty($email)) { $err .= "Email is empty<br>";
}ELSE{
IF (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$err .= "Email is not valid<br>";
}
}
IF (empty($password)) { $err .= "Password is empty<br>"; }
IF (!empty($err)) {
// there are errors
echo("<p>".$err."</p>");
}ELSE{
// No errors
$uemail = mysql_real_escape_string($email);
$upass = mysql_real_escape_string(md5($password));
$result = mysql_query("SELECT * FROM users WHERE emailAddress='$uemail' && password = '$upass'");
IF ($result) {
// set session
$row = mysql_fetch_array($result);
$_SESSION['user'] = $row['user_id'];
}ELSE{
echo("<p>Email address and or your password was incorrect.<br>If you do not have an account please create one.</p>");
}
// Close DB connection
mysql_close($Your_db_connection);
// redirect if session is set
IF (isset($_SESSION['user'])) { header("Location: home.php"); }
}
}ELSE{
// form not submitted
}
?>
You can use html5 validation for login form use required attributes for blank input field validation this validation is very easy and user friendly please use this way
i'm worried about the security of my form. The idea is to make a form to participate in a contest in facebok. Basically just firstname, lastname, email. I've been searching through topics and there is a lot of info about security but i can't figure out what is enough security?
I know that there will always be a risk that someone finds a way to abuse the security, but i'd like to find a solution, which blocks the most of them. Also if there are obvious mistakes, please let me know.
Here is my code and all help and guidance is appreciated.
<?php
$dsn = 'mysql:dbname=dbname;host=localhost';
$user = '';
$password = '';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$firstErr = $lastErr = $emailErr = "";
$first = $last = $email = "";
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["first"])) {
$firstErr = "Name is required";
echo "<p>Firstname: $firstErr</p>";
} else {
$first = test_input($_POST["first"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$first)) {
$firstErr = "Only letters and white space allowed";
echo "<p>Firstname: $firstErr</p>";
}
}
if (empty($_POST["last"])) {
$lastErr = "Name is required";
echo "<p>Lastname: $lastErr</p>";
} else {
$last = test_input($_POST["last"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$last)) {
$lastErr = "Only letters and white space allowed";
echo "<p>Lastname: $lastErr</p>";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
echo "<p>Email: $emailErr</p>";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
echo "<p>Email: $emailErr</p>";
}
}
if ($firstErr == false && $lastErr == false && $emailErr == false) {
$query = "INSERT INTO contactstable (first,last,email) VALUES(:first,:last,:email)";
$statement = $dbh->prepare($query);
$statement->execute(array(
':first'=> $first,
':last'=> $last,
':email'=> $email
));
echo "<p>Thank you for participating!</p>";
}
else {
echo "Fix the missing or incorrect lines.";
}
}
?>
You are using PDO, it already implements the security measures for 1st order injection and when the queries are parametrized the 2nd order also prevented(2nd order injection means data has been cycled through the database once before being included in a query).
But there is no harm if you implements validations for the inputs.
im trying to create a form that validates the input fields then sends the data into a mysql database. i can get either the input validation to work, or the data inserted into the database, but not both.. heres my code:
<?php require_once('../php/pdo_connect.php');
// define variables and set to empty values
$first_name_err = $last_name_err = $cell_err = $email_err = FALSE;
$first_name = $last_name = $cell = $email = FALSE;
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["first_name"]))
{$first_name_err = "First name is required";}
else
{
$first_name = test_input($_POST["first_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$first_name))
{
$first_name_err = "Please don't use hypens or other special characters";
}
}
if (empty($_POST["last_name"]))
{$last_name_err = "Last name is required";}
else
{
$last_name = test_input($_POST["last_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$last_name))
{
$last_name_err = "Please don't use hypens or other special characters";
}
}
if (empty($_POST["cell"]))
{$cell_err = "Phone number is required";}
else
{
$cell = test_input($_POST["cell"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[\+0-9\-\(\)\s]*$/",$cell))
{
$cell_err = "Invalid cell phone number";
}
}
if (empty($_POST["email"]))
{$email_err = "Email address is required";}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$email_err = "Invalid email format";
}
}
if ($first_name_err = false){
//insert info into db
$query = $pdo->prepare("INSERT INTO `guestlist_page_requests` (first_name, last_name, cell, email) VALUES (?, ?, ? ,?)");
$query->bindValue(1, $first_name);
$query->bindValue(2, $last_name);
$query->bindValue(3, $cell);
$query->bindValue(4, $email);
$query->execute();
header('Location: ../index.php');
}else{
//not enough data to submit to db
}
}
i tried a few differant variations of this line:
if ($first_name_err = false){
but im not really sure what i should be putting here?
this line almost makes it work:
if (!empty($_POST['first_name']) && !empty($_POST['last_name']) && !empty($_POST['cell']) && !empty($_POST['email'])){
but then it submits the data with the errors unless one of the fields is empty.
this also doesnt seem to work right:
if ($first_name_err = false){