How can I short php code? - php

How can i modify my code to work "smarter" without so many if-loops? I am attaching what i have tried so far.
$error1 = $error2 = $error3 = $error4 = $error5 = $error6 = $error7 = $error8 = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$error1 = "fill in fname";
}
if (empty($_POST["lname"])) {
$error2 = "fill in lname";
}
if (empty($_POST["street"])) {
$error3 = "fill in street";
}
if (empty($_POST["city"])) {
$error4 = "fill in city";
}
if (empty($_POST["postcode"])) {
$error5 = "fill in postcode";
}
if (empty($_POST["country"])) {
$error6 = "fill in country";
}
if (empty($_POST["email"])) {
$error7 = "fill in email";
}
if (empty($_POST["phone"])) {
$error8 = "fill in phone";
}
}
Thanks in advance!

Try this:
$errors = array();
$inputs = array("fname", "lname", "street", "city", "postcode", "country", "email", "phone");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
foreach($_POST as $key => $arg) {
if(in_array($key, $inputs) && empty($arg)){
$errors[] = "fill in " . $key;
}
}
}

Please check this
$formfields = array('fname','lname','street','city','postcode','country','email','phone');
$errMsg = "";
if(isset($_POST) && count($_POST)>0){
foreach($_POST as $key => $val){
if(in_array($key, $formfields)){
if (empty($_POST[$key])) { $errMsg[] = "fill in ". $key; }
}
}
}
if(count($errMsg)>0)
echo implode("<br/>",$errMsg);

Related

Register new user - Problem with SQLSTATE

Implementing a simple register system and after implementing try to test it I get this error message:
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
My code for register user is:
<?php
session_start();
require_once('config.php');
if(isset($_POST['submit']))
{ if(isset($_POST['name'],$_POST['lastname'],$_POST['email'],$_POST['pass']) && !empty($_POST['name']) && !empty($_POST['lastname']) && !empty($_POST['email']) && !empty($_POST['pass']))
{
$name= trim($_POST['name']);
$lastname = trim($_POST['lastname']);
$email= trim($_POST['email']);
$pass= trim($_POST['pass']);
$options = array("cost"=>4);
$hashPassword = password_hash($pass,PASSWORD_BCRYPT,$options);
$date = date('Y-m-d H:i:s');
if(filter_var($email, FILTER_VALIDATE_EMAIL))
{
$sql = 'SELECT * FROM members WHERE email = :email';
$stmt = $pdo->prepare($sql);
$p = ['email'=>$email];
$stmt->execute($p);
if($stmt->rowCount() == 0)
{
$sql = "insert into members (name, lastname, email, `pass`, created_date,updated) values(:name,:lastname,:email,:pass,:created_date,:updated)";
try{
$handle = $pdo->prepare($sql);
$params = [
':name'=>$name,
':lastname'=>$lastname,
':email'=>$email,
':pass'=>$hashPassword,
':created_date'=>$date,
':updated'=>$date
];
$handle->execute($params);
$success = 'Successfull registration!';
}
catch(PDOException $e){
$errors[] = $e->getMessage();
}
}
else
{
$valName= $name;
$valLastname= $lastname;
$valEmail= '';
$valPass= $pass;
$errors[] = 'Email address already registered';
}
}
else
{
$errors[] = "Email address is not valid";
}
}
else
{
if(!isset($_POST['name']) || empty($_POST['name']))
{
$errors[] = 'Error 1!';
}
else
{
$valIme= $_POST['name'];
}
if(!isset($_POST['lastname']) || empty($_POST['lastname']))
{
$errors[] = 'Error 2!';
}
else
{
$valLastname= $_POST['lastname'];
}
if(!isset($_POST['email']) || empty($_POST['email']))
{
$errors[] = 'Error 4!';
}
else
{
$valEmail= $_POST['email'];
}
if(!isset($_POST['pass']) || empty($_POST['pass']))
{
$errors[] = 'Error 5!';
}
else
{
$valPass= $_POST['pass'];
}
}
}
?>
I don't get where the problem could be. I think is that I need to change the date value inserted to the database, and that could be a problem. Can someone test this code and tell me where is the problem?

my form submits a bad entry even though it gets validated, how can I prevent this?

Using PHP, the validation on my form is correct and I even use a redirect header when the form is submitted correctly, this part works just fine, however, when the form is validated or showing errors a entry is submitted when it should not, is their anything I need to be added to my code base to fix this bug, take a look at my code below..
<?php
$e_first = ""; $e_last = ""; $e_email = ""; $success = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
require_once("config.php");
require_once("database.php");
require_once("controller.php");
$firstname = sanitize($_POST['firstname']);
$lastname = sanitize($_POST['lastname']);
$email = sanitize($_POST['email']);
$submit = sanitize($_POST['submit']);
if (empty($firstname)) {
$e_first = "First Name is required";
} else {
$firstname;
if (!preg_match("/^[a-zA-Z ]*$/", $firstname)) {
$e_first = "Only letters and white space allowed";
}
}
if (empty($lastname)) {
$e_last = "Last Name is required";
} else {
$lastname;
if (!preg_match("/^[a-zA-Z ]*$/", $lastname)) {
$e_last = "Only letters and white space allowed";
}
}
if (empty($email)) {
$e_email = "Email Address is required";
} else {
$email;
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$e_email = "Invalid Email Address";
}
}
$users = [
'firstname' => $firstname,
'lastname' => $lastname,
'email' => $email
];
$control = new Controller();
$control->addCustomer($users);
if (isset($submit)) {
switch (false) {
case !empty($firstname) || $firstname == $e_first :
$success = "";
break;
case !empty($lastname) || $lastname == $e_last :
$success = "";
break;
case !empty($email) || $email == $e_email :
$success = "";
break;
default :
$success = "Thank you $firstname $lastname";
header("Location: success.php");
break;
}
}
}
function sanitize($data) {
$data = htmlspecialchars($data);
$data = stripslashes($data);
$data = strip_tags($data);
$data = trim($data);
return $data;
}
?>
The bit where you add the user should be after you check for errors
default :
$control = new Controller();
$control->addCustomer($users);
$success = "Thank you $firstname $lastname";
header("Location: success.php");
break;

how to store form validation errors in an array

If I have some basic form validations, (just using empty() for simplicities sake) and want to put those error messages into an array, how would I achieve this?
$errors = array();
$response = array();
if(empty($_POST['name'])) {
$errors['name'] = "Name required";
}
if(empty($_POST['email'])) {
$errors['email'] = "Email required";
}
$response['errors'] = $errors;
if(!empty($errors)) {
$response['success'] = false;
$response['message'] = "fail";
} else {
$response['success'] = true;
$response['message'] = "<div class='alert alert-success'>Success</div>";
}
echo json_encode($response);
}
$message = [];
if(empty($_POST['name'])) {
array_push($message , "Name required <br />");
}
if(empty($_POST['email'])) {
array_push($message , "Email required <br />");
}
if(!empty($message)) {
foreach ( $message as $str)
echo "<div class='alert alert-danger'>" . $str . "</div>";
} else {
// success
}

How to correctly use php header(Location: ) [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 5 years ago.
I have read several answers and questions, however, I still cannot seem to get my header() to work. This is just a simple contact form, and This is my last step to send guests to a thankyou page. What am I missing.
<?php
$fname = $lname = $cname = $email = $budget = $services = "";
$error_counter = 0;
$error_report = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['fname'])) {
$fname_error = 'Please provide your first name.';
$error_counter++;
} else {
$fname = test_input($_POST['fname']);
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$fnameErr = "Only letters and white space allowed";
$error_counter++;
}
}
if (empty($_POST['lname'])) {
$lname_error = 'Please provide your last name.';
$error_counter++;
} else {
$lname = test_input($_POST['lname']);
if (!preg_match("/[a-zA-Z \.]/",$lname)) {
$lnameErr = "Only letters and white space allowed";
$error_counter++;
}
}
if (empty($_POST['cname'])) {
$cname = '';
} else {
$cname = test_input($_POST['cname']);
if (!preg_match("/^[a-zA-Z0-9 \.]*$/",$cname)) {
$cnameErr = "Only letters and white space allowed";
$error_counter++;
}
}
if (empty($_POST['phone'])) {
$phone = '';
} else {
$phone = test_input($_POST['phone']);
if (!preg_match("/^[()\-0-9 \.]*$/",$phone)) {
$phoneErr = "Please use only the following: ( ) - . 0-9.";
$error_counter++;
}
}
if (empty($_POST['email'])) {
$email_error = 'Please provide an email so that I can get back in touch with you.';
$error_counter++;
} else {
$email = test_input($_POST['email']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { //validate email
$emailErr = "Invalid email format";
$error_counter++;
}
}
if (empty($_POST['budget'])) {
$budget_error = 'Please provide an estimated budget.';
$error_counter++;
} else {
$budget = test_input($_POST['budget']);
}
if (empty($_POST['textarea'])) {
$textarea = '';
} else {
$textarea = test_input($_POST['textarea']);
}
if (isset($_POST['new-website'])) {
$services = $services."New Website<br>";
}
if (isset($_POST['website-redesign'])) {
$services = $services."Website Re-design<br>";
}
if (isset($_POST['mobile-website'])) {
$services = $services."Mobile Website<br>";
}
if (isset($_POST['online-resume'])) {
$services = $services."Online Resume<br>";
}
if (isset($_POST['non-profit-website'])) {
$services = $services."Non-profit Website<br>";
}
if (isset($_POST['seo'])) {
$services = $services."SEO<br>";
}
if (isset($_POST['google-adwords'])) {
$services = $services."Google AdWords<br>";
}
if (isset($_POST['graphics-design'])) {
$services = $services."Graphics Design<br>";
}
if (isset($_POST['other'])) {
$services = $services."Other<br>";
}
$fname = test_input($_POST['fname']);
$lname = test_input($_POST['lname']);
$cname = test_input($_POST['cname']);
$phone = test_input($_POST['phone']);
$email = test_input($_POST['email']);
$budget = test_input($_POST['budget']);
$textarea = test_input($_POST['textarea']);
if ($error_counter == 0) {
$to = "dpeaches96#gmail.com";
$subject = "Website Contact Peachwebdev";
$name_final = "Name: ".$fname." ".$lname."<br><br>";
$company_final = "Company: ".$cname."<br><br>";
$phone_final = "Phone Number: ".$phone."<br><br>";
$email_final = "Email: ".$email."<br><br>";
$budget_final = "Est. Budget: ".$budget."<br><br>";
$services_final = "Services: <br>".$services."<br><br>";
$textarea_final = "Comments: ".$textarea."<br><br>";
$message = $name_final.$company_final.$phone_final.$email_final.$budget_final.$services_final.$textarea_final;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: '.$email;
mail($to,$subject,$message,$headers);
header("Location: http://www.peachwebdev.com/pages/thankyou.html");
exit;
} else {
echo '<script type="text/javascript"> alert(\'There were errors in your form. Please try again.\'); </script>';
$error_report = "<div class='alert alert-danger'>There were errors in your form, please correct and submit again.</div>";
}
}
function test_input($data) {
$data = htmlspecialchars($data);
$data = trim($data);
$data = stripslashes($data);
return $data;
}
?>
And I am aware that my code can probably made better, so if there are suggestions on simplifying or condensing, I would gladly appreciate it!
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
Refer the documentation.
One way to test is replace the call to header() in your code with a simple echo with some custom string (say 'XYZXYZ'). Then look at the raw output and check if there are any characters before this string.

How to validate forms

I am new in PHP programming and I am creating my first registration and login form. I did everything but there is one problem: How I must sort the code. I tried in lots of ways but it is messed up.
if (filter_input_array(INPUT_POST)) {
if (preg_match('/\s/', $name)) {
$errorName = "Names doesn't contain whitespaces";
$mainError = true;
}
$sql = "SELECT name FROM register WHERE name='$name'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if (mysqli_num_rows($result) == 1) {
$errorName = 'This name is already registered';
$mainError = true;
}
if (mb_strlen($name) > 0 AND mb_strlen($name) < 3) {
$errorName = 'Name too short';
$mainError = true;
}
if (mb_strlen($name) > 15) {
$errorName = 'Name too long';
$mainError = true;
}
if ($name == '') {
$errorName = 'This field is REQUIRED';
$mainError = true;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errorEmail = "Invalid email";
$mainError = true;
}
if (preg_match('/\s/', $pass1)) {
$errorName = "Password mustn't contain whitespaces";
$mainError = true;
}
if (mb_strlen($pass1) > 0 AND mb_strlen($pass1) < 6) {
$errorPass1 = 'Password too short';
$mainError = true;
}
if (mb_strlen($pass1) > 20) {
$errorPass1 = 'Password too long';
$mainError = true;
}
if ($pass1 == '') {
$errorPass1 = 'This field is REQUIRED';
$mainError = true;
}
if ($pass1 != $pass2) {
$errorPass2 = "Passwords don't match";
$mainError = true;
}
if ($pass2 == '') {
$errorPass2 = 'This field is REQUIRED';
$mainError = true;
}
if (!$mainError) {
$feedback = 'You registered successfully!';
}
}
I want to know what must be first

Categories