cant validate and insert date on form - php

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){

Related

Prevent storing invalid information in sql database

I have made this form where users can input various information,Everything is fine i am checking for different errors also but the problems is if user inputs email with a invalid email format and when pressing sumbit button it gives error invalid email format which is fine but mydatabase stores the invalid email also,How to prevent storing some invalid information?? And i am new to programming.
Thanks in advance.
$nameErr = $adressErr = $emailErr = $passwordErr = $genderErr = "";
$name = $adress = $email = $password = $gender = "";
if(isset($_POST['sumbit'])){
if (empty($_POST["name"])){
$nameErr = "Name is required";
}else{
$name = $_POST["name"];
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["adress"])){
$adressErr = "Adress is required";
}else{
$adress = $_POST["adress"];
}
if(empty($_POST["email"])){
$emailErr = "Email is required";
}else{
$email = $_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"])){
$passwordErr = "Password is required";
}else{
$password = $_POST["password"];
}
if(empty($_POST["gender"])){
$genderErr = "Gender is required";
}else{
$gender = $_POST["gender"];
}
}
$sql = "INSERT INTO users(name,adress,email,password,gender)VALUES(:name,:adress,:email,:password,:gender)";
$statement = $conn->prepare($sql);
$statement->bindParam(":name",$name);
$statement->bindParam(":adress",$adress);
$statement->bindParam(":email",$email);
$statement->bindParam(":password",$password);
$statement->bindParam(":gender",$gender);
$statement->execute();
?>
Create a Boolean on top
$hasError = false;
In case of all error, set Boolean true as $hasError = true;
Before sql query :
if($hasError){
// redirect to form page -- pass the ERROR in the url as get and then show the error on form page
}
else{
// execute query code
}
It's good have server side checks, you can add a lot of validation on client side too.
Client side checks
For email, you can use type='email' instead of type='text'. Similarly, you can have maxlength, required, etc. to avoid erroneous data.
You first checked all field validation one by one and then executed your insert query. That's why always creating a new rows into database in both cases inputs are valid or invalid.
you should put your insertion query in the block if only inputs are valid.
Try this -
<?php
$nameErr = $adressErr = $emailErr = $passwordErr = $genderErr = "";
$name = $adress = $email = $password = $gender = "";
$error = array();
if(isset($_POST['sumbit'])){
if (empty($_POST["name"])){
$error[] = "Name is required";
}else{
$name = $_POST["name"];
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$error[] = "Only letters and white space allowed";
}
}
if(empty($_POST["adress"])){
$error[] = "Adress is required";
}else{
$error[] = $_POST["adress"];
}
if(empty($_POST["email"])){
$error[] = "Email is required";
}else{
$email = $_POST["email"];
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error[] = "Invalid email format";
}
}
if(empty($_POST["password"])){
$error[] = "Password is required";
}else{
$password = $_POST["password"];
}
if(empty($_POST["gender"])){
$error[] = "Gender is required";
}else{
$gender = $_POST["gender"];
}
}
if(empty($error)){
$sql = "INSERT INTO users(name,adress,email,password,gender)VALUES(:name,:adress,:email,:password,:gender)";
$statement = $conn->prepare($sql);
$statement->bindParam(":name",$name);
$statement->bindParam(":adress",$adress);
$statement->bindParam(":email",$email);
$statement->bindParam(":password",$password);
$statement->bindParam(":gender",$gender);
$statement->execute();
}else{
foreach ($error as $key => $value) {
echo '<li>'.$value.'</li>';
}
}
?>

DB not updating after putting the prepared statment in the code

So I have decided to put the prepared statement in my code and when I fill the information with all the valid details, a message pops up saying registration successful but no data actually goes in the Database
Here is the function code that I have;
//check if form is submitted
if (isset($_POST['signup'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
//name can contain only alpha characters and space
if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
$error = true;
$name_error = "Name must contain only alphabets and space";
}
if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$error = true;
$email_error = "Please Enter Valid Email ID";
}
if(strlen($password) < 6) {
$error = true;
$password_error = "Password must be minimum of 6 characters";
}
if($password != $cpassword) {
$error = true;
$cpassword_error = "Password and Confirm Password doesn't match";
}
if (!$error)
{
// prepare and bind
$stmt = $con->prepare("INSERT INTO users (name,email,password) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $name, $email, $password);
if($stmt->execute = true) {
$successmsg = "Successfully Registered! <a href='login.php'>Click here to Login</a>";
} else {
$errormsg = "Error in registering...Please try again later!";
}
}
}
?>
The Db structure in my php my admin;
id(int 8)
name(varchar 30)
email(varchar 60)
password(varchar 40)
I would appreciate a help, and thanks in advance!

Empty form submitting to the database?

When I click the submit button without filling the form, a new entry appears on database with the ID but the form keep validating and showing the user, this field is required but why the form is still submitting to the database?
Here is my code, kindly help, I am new in PHP and very tired of solving such problem.
<?php
include 'dbc.php';
// define variables and set to empty values
$name_error = $email_error = $phone_error = $url_error = $message_error = "";
$name = $email = $phone = $message = $url = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST["name"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$phone_error = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
// check if e-mail address is well-formed
}
if (empty($_POST["url"])) {
$url_error = "Website url is required";
} else {
$url = test_input($_POST["url"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$url)) {
$url_error = "Invalid URL";
}
}
if (empty($_POST["message"])) {
$message_error = "Message field is required";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' and $phone_error == '' and $url_error == '' and $message_error == ''){
$message = 'Hello Ladies';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message .= "$key: $value\n";
}
$to = 'sample#email.com';
$subject = 'Contact Form Submit';
if (mail($to, $subject, $message)){
$success = "Message sent, thank you for contacting us!";
}
}
$query = "INSERT INTO clients(name,email,phone,url,message) ";
$query .= "VALUES('$name', '$email', '$phone', '$url', '$message') ";
$create_user = mysqli_query($mysqli, $query);
if (!$create_user) {
die("QUERY FAILED. " . mysqli_error($mysqli));
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
I hope I don't get downvote.
The only check actually being made before the query is run, is
if ($_SERVER["REQUEST_METHOD"] == "POST") {
which means that the only requirement for inserting values, is that the form is sent over POST, nothing else. This can be checked with a proper editor and seeing what brackets are wrapped around your query. You do some checks earlier in the code to validate and check the input, but this doesn't tell if the query should be run or not.
If you move the closing-bracket } of the following if-block
if ($name_error == '' and $email_error == '' and $phone_error == '' and $url_error == '' and $message_error == ''){
until after the query is performed, the query will only run if it passed all your checks. (place it after the following snippet)
if (!$create_user) {
die("QUERY FAILED. " . mysqli_error($mysqli));
}
In other remarks, your test_input() is rubbish (really) and you shouldn't use it. Parameterize your queries instead and filter the input with proper functions. There are validation filters and sanitation filters already implemented in PHP, you should use them if you need to.
You should prepare and bind the values of your queries using mysqli::prepare(), this will handle any issues dealing with quotes and protect your database against SQL injection.
References
mysqli::prepare()
How can I prevent SQL injection in PHP?

Redirecting to success page after validation

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.

Php + mysql insert data securely

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.

Categories