PHP validating multiple required input fields - php

I am validating some input fields before sending the email. I am using for each to loop through the array faster and check that every single input is not empty and return it as a response in jquery to show the errors. The problem is that email and message inputs are not being validated. Emails are being sent even if the inputs are empty.
the array elements come from the input name attributes from the html.
function e_($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
#required fields
$required = array('name', 'email','lname','message','country' , 'city' ,'adcategory','plan' ,'company');
$success = false;
#non required fields
$website = e_($_POST['website']);
$addr = e_($_POST['address']);
foreach($required as $field) {
if (empty($_POST[$field]))
{
$success = false;
}
else if(!empty($_POST[$field])){
$success = true;
$name = e_($_POST['fname']);
$email = e_($_POST['email']); #this has issue
$lname = e_($_POST['lname']);
$msg = e_($_POST['message']); #this has issue
$country = e_($_POST['country']);
$city = e_($_POST['city']);
$adCategory = e_($_POST['adcategory']);
$plan = e_($_POST['plan']);
$companyName = e_($_POST['company']);
}
}
if($success)
echo "success";
else if (!$success)
echo json_encode(['errors'=>true]); #this will be manipulated in jquery

The problem is that you set $success = true; whenever you find a required field, and this undoes the $success = false; for a previous field. You also process all the fields in the else if, even though that just means that one of the required fields was found.
$success = true;
foreach ($required as $field) {
if (empty($_POST[$field])) {
$success = false;
$missing_field = $field;
break;
}
}
if (!$success) {
echo json_encode(['errors'=>true, 'missing' => $missing_field]);
exit();
}
$name = e_($_POST['fname']);
$email = e_($_POST['email']); #this has issue
$lname = e_($_POST['lname']);
$msg = e_($_POST['message']); #this has issue
$country = e_($_POST['country']);
$city = e_($_POST['city']);
$adCategory = e_($_POST['adcategory']);
$plan = e_($_POST['plan']);
$companyName = e_($_POST['company']);
echo "Success";

Your foreach loop is wrong. You have your if statement that checks if it's not empty inside your for loop that checks if it's empty. You need to check to see if all the values are empty first then run that if statement.
$success = true;
foreach($required as $field) {
if (empty($_POST[$field]))
{
$success = false;
break;
}
}
if($success)
{
// set your variables
} else {
// don't set your variables
}

Related

AngularJs - PHP POST issue

I am trying to make a post request with angularjs to php. The post response is always 200 OK and the returned 'data' variable in the response is empty always. I am kind of new at this as you can see, what am I doing wrong here?
AngularJs code:
$scope.postData = function(){
$http.post('send.php', $scope.data).then(function(response){
console.log(response);
});
}
PHP:
$form_data = json_decode(file_get_contents("php://input"));
$data = array();
$error = array();
if(empty($form_data->fullName)){
$error["fullName"] = "Your name is required";
}
if(empty($form_data->email)){
$error["email"] = "Your email is required";
}
if(empty($form_data->message)){
$error["message"] = "Message is required";
}
if(!empty($error)){
$data["error"] = $error;
} else {
$data["message"] = "Ok";
}
You need to echo data back to the client, in your code you not returning anything back hence the response is empty.
<?php
$form_data = json_decode(file_get_contents("php://input"));
$data = array();
$error = array();
if(empty($form_data->fullName)){
$error["fullName"] = "Your name is required";
}
if(empty($form_data->email)){
$error["email"] = "Your email is required";
}
if(empty($form_data->message)){
$error["message"] = "Message is required";
}
if(!empty($error)){
$data["error"] = $error;
} else {
$data["message"] = "Ok";
}
echo json_encode($data); // return data back to the client

How to access variable value from another php script

I have read so many pages and am stuck on this for the past three hours now because it just won't work.
I keep getting Notice: Undefined index: firstname
here is the bulk of the segment that isn't working:
$errMsg = "";
function sanitise($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST["firstname"]))
{
$firstname = $_POST["firstname"];
$firstname = sanitise($firstname);
if (!preg_match("/^[A-Za-z \-]+$/",$firstname))
{
$errMsg .= "First name must contain only letters or hyphens.<br/>";
}
if (strlen($firstname) > 40)
{
$errMsg .= "First name cannot be over 40 characters long.<br/>";
}
} else {
$errMsg .= "First name cannot be empty.<br/>";
$firstname = "";
}
if ($errMsg != "")
{
header("Location: fix_order.php?firstname=$firstname");
}
this is the code on fix_order.php where I want to access the variables.
$firstname = $_GET["firstname"];
echo "<p>firstname is $firstname .</p>";
I have tested the $firstname on the first page and it echo's the values just fine.
change your code to
$firstname = $_GET["errMsg"];
echo "<p>firstname is $firstname .</p>";
You can't access $firstname as this is the value not the key. errMsg is the key you should use.
Looks fine to me, it should work.
To get rid of the notice, you need to define variable by using isset()
$firstname = isset($_GET['firstname']) ? $_GET['firstname'] : '';
OR
if(isset($_GET['firstname'])) {
$firstname = $_GET['firstname'];
} else {
$firstname = '';
}

read JSON input in slim framework

i am new to slim framework following a tutorial i managed to get post data to my API.but when i tried to send data as JSON it gives me an error.I tried to accpt JSON request as follows what is the correct syntax to achive this.i get error as Required field(s) name, email, password is missing or empty
$app->post('/login', function() use ($app) {
// check for required params
$json = $app->request->getBody();
$data = json_decode($json, true);
verifyRequiredParams(array('name','email', 'password'));
how i can get json data from a post request in my API from an JSON array like
{
"name":"usertest",
"email":"xxxx#xxx.xxx",
"password":"xxxxxx"
}
can i use verifyRequiredParams(array('name','email', 'password')); and $name = $app->request->post('name'); if request come as a JSON.
To read the request data you can use your $data property. It should be an object so you can use it like this:
$name = $data->name;
$email = $data->email;
EDIT:
Use $data = json_decode($json) instead of $data = json_decode($json, true) to convert the json data to object instead of an associative array.
the problem was with placing my verifyRequiredParams function i think.i fixed the issue from following code in case any one had same issue.
$app->post('/login', function() use ($app) {
if($app->request->headers->get('Content-Type')=='application/json'){
$json = $app->request->getBody();
verifyRequiredParamsjson(array('email','password'),$json);
$data = json_decode($json);
// check for required params
$email = $data->email;
$password = $data->password;
}
else{
// check for required params
verifyRequiredParams(array('email', 'password'));
// reading post params
$email = $app->request->post('email');
$password = $app->request->post('password');
}
$response = array();
$db = new DbHandler();
// check for correct email and password
if ($db->checkLogin($email, $password)) {
// get the user by email
$user = $db->getUserByEmail($email);
if ($user != NULL) {
$response["error"] = false;
$response['name'] = $user['name'];
$response['email'] = $user['email'];
$response['apiKey'] = $user['api_key'];
$response['createdAt'] = $user['created_at'];
} else {
// unknown error occurred
$response['error'] = true;
$response['message'] = "An error occurred. Please try again";
}
}
else{
$response['error'] = true;
$response['message'] = 'Login failed. Incorrect credentials';
}
echoRespnse(200, $response);
});
required parameter check,
function verifyRequiredParams($required_fields) {
$error = false;
$error_fields = "";
$request_params = array();
$request_params = $_REQUEST;
// Handling PUT request params
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
$app = \Slim\Slim::getInstance();
parse_str($app->request()->getBody(), $request_params);
}
foreach ($required_fields as $field) {
if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
$error = true;
$error_fields .= $field . ', ';
}
}
if ($error) {
// Required field(s) are missing or empty
// echo error json and stop the app
$response = array();
$app = \Slim\Slim::getInstance();
$response["error"] = true;
$response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
echoRespnse(400, $response);
$app->stop();
}
}

PHP Form data validation issue

I am making a basic content management system and I have got stuck with the validation of data being entered into a form.
For example, one form is to edit the name of a subject (in the navigation menu). The form contains a few different pieces of data but the main focus is the "menu_name" field (name of subject).
On form submission data in "menu_name" should be checked to ensure it is not empty and if it is then give an error. What is happening is that the form validation doesn't seem to be working as when I enter nothing the script continues to edit the subject name, in this case making it blank.
This is the script that is executed on form submission:
if (isset($_POST['submit']))
{
// Process the form
// Validations
$required_fields = array("menu_name", "position", "visible");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 30);
validate_max_lengths($fields_with_max_lengths);
// If errors occured, redirect
if(empty($errors))
{
// Perform update
// Assign POST data to variables
$id = $current_subject["id"];
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
// 2. Perform database query
$query = "UPDATE subjects SET ";
$query .= "menu_name = '{$menu_name}', ";
$query .= "position = '{$position}', ";
$query .= "visible = '{$visible}' ";
$query .= "WHERE id = {$id} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) >= 0)
{
// Success
$_SESSION["message"] = "Subject updated.";
redirect_to("manage_content.php");
}
else
{
// Failure
$message = "Subject update failed.";
}
}
}
The data is then checked by two custom validation functions as you can see, the second one is not my concern but the first function validate_presences(), here is the function:
function validate_presences($requried_fields)
{
GLOBAL $errors;
foreach($required_fields as $field)
{
$value = trim($_POST[$field]);
if (!has_presence($value))
{
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
You can see there that it references the has_presence() function, which is:
function has_presence($value)
{
return isset($value) && $value !== "";
}
If anyone has any ideas on what is wrong, any help is appreciated!
Just ask if you need some more information.
Thanks in advance!
Why don't you just return the error array instead of making it global? I think it will resolve your problem instantly ;)
function validate_presences($requried_fields)
{
$errors = array();
foreach($required_fields as $field)
{
$value = trim($_POST[$field]);
if (!has_presence($value))
{
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
return $errors;
}
Now set $errors = validate_presences($required_fields); and your ready to go!
It's not recommended to use variables in a global way like this. Rather pass the errors variable by reference to the validation functions.
$errors = array();
function validate_presences($requried_fields, &$errors)
{
foreach($required_fields as $field)
{
$value = trim($_POST[$field]);
if (!has_presence($value))
{
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
$required_fields = array("menu_name", "position", "visible");
validate_presences($required_fields, $errors);
$fields_with_max_lengths = array("menu_name" => 30);
validate_max_lengths($fields_with_max_lengths, $errors);
// If errors occured, redirect
if(empty($errors))
{

Looping correctly though array

Okay so I'm looping through the results that contains two question IDs and two answers and I'm trying to match the two answers with the two answers from the form submission.
I'm not sure what I'm doing wrong.
<?php
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
//Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = false;
if (trim($_POST['answer1']) == '') { $errors = true; }
if (trim($_POST['answer2']) == '') { $errors = true; }
// Error checking, make sure all form fields have input
if ($errors) {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => $errors, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc,$_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc,$_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc,$_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc,$_POST['question1']);
$question2 = mysqli_real_escape_string($dbc,$_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc,$query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if (($answer == $answer1Post) && ($answer == $answer2Post)) {
} else {
$errors = true;
$message = "Your answers did not match the answers inside the database!";
$output = array('errorsExist' => $errors, 'message' => $message);
}
}
} else {
$errors = true;
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => $true, 'message' => $message);
}
}
}
//Output the result
$output = json_encode($output);
echo $output;
?>
Since your question is not clear in the first place, so I'm assuming that the question you are asking is "why you're not getting any matching results, when you've the correct answers in the database?". Please correct me, if this is wrong.
The logic can be like this:-
<?php
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
// Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = false;
if (trim($_POST['answer1']) == '') { $errors = true; }
if (trim($_POST['answer2']) == '') { $errors = true; }
// Error checking, make sure all form fields have input
if ($errors) {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => $errors, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc, $_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc, $_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc, $_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc, $_POST['question1']);
$question2 = mysqli_real_escape_string($dbc, $_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc, $query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if ($answer == $answer1Post) {
// The first answer is correct
$errors = false;
$message = "Your first answer is correct!";
} else if ($answer == $answer2Post) {
// The second answer is correct
$errors = false;
$message = "Your second answer is correct!";
} else {
$errors = true;
$message = "Your answers did not match the answers inside the
}
$output = array('errorsExist' => $errors, 'message' => $message);
}
} else {
$errors = true;
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => $true, 'message' => $message);
}
}
}
// Output the result
$output = json_encode($output);
echo $output;
?>
It's better to have more segregation of logical conditions. In this case, it's your two answers to check for.
Hope it helps.

Categories