I have a user defined function, it takes one argument as an array for the form required fields. It checks if these fields are empty or not. If they are empty it will return a message and stop processing the form.
<?php
function check_required_fields($required_array) {
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
}
}
return "You have errors";
}
$required_array = array('name', 'age');
if (isset($_POST['submit'])) {
echo check_required_fields($required_array);
}
?>
<html>
<body>
<form action="#" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
The function is returning this error even when the form required fields are filled? how to fix this?
How can i use just use the function with out writing the word echo before its name?
I want to use this function so i don't have to manually write the if and else statement for every field in the form.
I think you want to do like this?
function check_required_fields($required_array) {
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
return "You have errors"; //This indicates that there are errors
}
}
}
or why not just:
function check_required_fields($required_array) {
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname])) {
return "You have errors"; //This indicates that there are errors
}
}
}
UPDATE:
Change:
$required_array = array('name', 'age'); //This just sets strings name and age into the array
to:
$required_array = array($_POST['name'], $_POST['age']); //This takes the values from the form
Related
I'm trying to create a function. which will check if the field is empty or not. If the input is empty it'll push an error for that input in the error array.
$errors = ["name" => "Name is required"];
like so
How can I do this?
function checkRequiredFields($fields = [], $errors = [])
{
foreach ($fields as $field) {
if (is_blank($field)) {
$errors[$field] = "$field is required";
}
}
}
btw here's how my is_blank function looks:
function is_blank($value)
{
return !isset($value) || trim($value) === '';
}
You can check that the field has been submitted and doesn't hold the empty string:
<?php
function check_required_fields($fields, &$errors) {
foreach($fields as $fieldname) {
if(isset($_POST[$fieldname]) && $_POST[$fieldname] === '') {
$errors[$fieldname][] = "'$fieldname' is required.";
}
}
}
check_required_fields(['email'], $errors);
?>
<form method='POST'>
<input type='text' name='name'>
<input type='email' name='email'>
<input type='submit'>
</form>
You can get the values of the input fields with
$field = $_GET["field"]; // or $_POST["field"]; depending of your form.
But you need to sanitize properly your input values for security reasons.
https://www.php.net/manual/fr/function.filter-input.php
The empty() function is also what you're looking for.
if (empty($field)) {
$errors[$field] = "$field is required";
}
Checkout the documentation : https://www.php.net/manual/fr/function.empty.php
Take a look at the isset() function also.
I apologize for this being a bit lengthy but I wanted to show the code and not leave anything out.
The Goal: The user submits a registration form that submits the form to a database which adds the info plus a unique string to the database. Once the user submits an email is sent to the user that contains a link to a php page that has that unique string as a URL identifier at the end like so:
xyz.com/activate.php?uid=292ca78b727593baad9a
When the user clicks that link they are taken that page where they will fill out another form and when they click submit it will activate their account.
The Problem: When the user goes to the link provided they receive an error from my validation page like so:
Undefined index: variable in process.php
BUT when the user deletes the URL identifier so the URL shows as:
xyz.com/activate.php
The user does not receive an error and the validation page (process.php) works properly. I have attempted to use the identifier with a $_GET['uid'] and checking if it exists before running the code but the result was the same. I cannot find an answer when attempting to google this issue so I apologize if this has been asked before.
The Question: Why does this work without the URL identifier but not with it? I do realize the URL identifier basically does a $_REQUEST when the page first loads which is what runs the process.php. Is there a way to prevent that?
So that you guys know the code I am working with I have posted it below.
activate.php:
<?php
// validate the form.
require_once('process.php');
$validation_rules = array(
'company_name' => array(
'required' => true,
'min-length' => 2
)
);
$db_error = '';
$validate = new validator();
$validate->validate($validation_rules);
if ($validate->validate_result()) {
// the validation passed!
}
?>
<div class="bg v-100 cm-hero-activate">
<div class="v-100">
<div class="v-set v-mid">
<form class="v-mid v-bg-white <?php if(!$validate->validate_result() && $_POST || !empty($error)) { echo "shake"; } ?>" name="activation" action="" method="post">
<fieldset>
<div class="form-content">
<div id="content">
<div class="form-inner in" data-id="1" data-name="activate">
<h1>ACTIVATE YOUR ACCOUNT</h1>
<div class="form-section">
<h2>Personal Info</h2>
<?php if (!empty($db_error)) {
echo $db_error;
} ?>
<div class="field-group">
<input type="text" id="company_name" class="field required" name="company_name" value="<?php $validate->form_value('company_name'); ?>">
<label for="company_name" class="placeholder">Company Name</label>
<?php $validate->error(array('field' => 'company_name', 'display_error' => 'single')); ?>
</div>
</div>
<div class="field-bottom">
<button name="submit" data-name="activate" class="bttn btn-dark btn-hover-gloss">ACTIVATE MY ACCOUNT</button>
</div>
</div>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
process.php:
<?php
class validator {
private $validation_rules;
private $errors = array();
private $validate_result = array();
public function validate($rules) {
$this->validation_rules = $rules;
if($this->validation_rules && $_REQUEST) {
foreach($this->validation_rules as $field => $rules) {
$result = $this->process_validation($field, $rules);
if($result == false) {
$this->validate_result[] = 0;
} elseif($result == true) {
$this->validate_result[] = 1;
}
}
}
}
public function form_value($field_name = '') {
if($this->validation_rules) {
if($_REQUEST && $_REQUEST[$field_name]) {
if(!$this->validate_result()) {
echo $_REQUEST[$field_name];
}
}
}
}
public function validate_result() {
if($this->validation_rules) {
if($_REQUEST) {
$final_result = true;
$length = count($this->validate_result);
for($i=0;$i < $length; $i++) {
if($this->validate_result[$i] == 0) {
$final_result = false;
}
}
return $final_result;
}
}
}
private function process_validation($field, $rules) {
$result = true;
$error = array();
foreach($rules as $rule => $value) {
if($rule == 'required' && $value == true) {
if(!$this->required($field, $value)) {
$error[] = "$field - required";
$result = false;
}
} elseif($rule == 'min-length') {
if(!$this->minlength($field, $value)) {
$error[] = "$field - minimun length is $value";
$result = false;
}
}
}
$this->errors[] = array($field => $error);
return $result;
}
public function error($data = '') {
if($this->validation_rules) {
if($_REQUEST) {
foreach($this->errors as $err) {
if(isset($data['field'])) {
foreach($err as $field => $field_error) {
if($data['field'] == $field) {
foreach($field_error as $error_data) {
if(isset($data['display_error']) == 'single') {
echo '<p class="error">' . $error_data . '</p>';
goto next;
} else {
echo '<p class="error">' . $error_data . '</p>';
}
}
next:
}
}
} else {
foreach($err as $field => $field_error) {
foreach($field_error as $error_data) {
if(isset($data['display_error']) == 'single') {
echo '<p class="error">' . $error_data . '</p>';
goto next1;
} else {
echo '<p class="error">' . $error_data . '</p>';
}
}
next1:
}
}
}
}
}
}
private function required($field, $value) {
if(empty($_REQUEST[$field])) {
return false;
} else {
return true;
}
}
private function minlength($field, $value) {
if(strlen($_REQUEST[$field]) < $value) {
return false;
} else {
return true;
}
}
?>
EDIT: it seems that the error is happening on the if statement in the min-length function: if(strlen($_REQUEST[$field]) < $value)
EDIT 2: This may also be of some use. The textbox is being filled with this: <br /><font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'><tr><th align='left' bgcolor='#f57900' colspan=
and underneath that I receive this error: Notice: Undefined index: company_name in C:\...\process.php on line 25 Call Stack #TimeMemoryFunctionLocation 10.0005369632{main}( )...\activate.php:0 20.0029403928validator->form_value( )...\activate.php:80 ">
Your $field_name doesn't exist in the $_REQUEST array which is why you are getting your undefined index error.
You are not checking if the value is set - just accessing it via $_REQUEST[$field_name] in your if statement.
Change
public function form_value($field_name = '') {
if($this->validation_rules) {
if($_REQUEST && $_REQUEST[$field_name]) {
if(!$this->validate_result()) {
echo $_REQUEST[$field_name];
}
}
}
}
To
public function form_value($field_name = '') {
if($this->validation_rules) {
if($_REQUEST && isset($_REQUEST[$field_name])) {
if(!$this->validate_result()) {
echo $_REQUEST[$field_name];
}
}
}
}
Unrelated Tips.
Aim for cleaner - and more concise readable code.
$input = [
'name' => 'Matthew',
];
$rules = [
'name' => 'required|string',
];
$v = (new Validator())->validate($input, $rules);
if ($v->fails()) {
// Do something with $v->errors();
return;
}
// Do something with validated input
Try and avoid using else or elseif wherever possible. This can be achieved by looking for the negative first, and exiting early. Try not to have too many levels of nesting. It makes your code extremely difficult to read and increases cyclomatic complexity.
Also - take a look at an MVC framework which should help you to structure your code. A good start would be something like Laravel https://laravel.com/ there are good tutorials on https://laracasts.com/
You are getting this error because you have logic like
if($this->validation_rules && $_REQUEST) {
In PHP, an empty array is falsy and a non-empty one, truthy.
$_REQUEST is a combination of $_GET, $_POST and $_COOKIE.
When you add the uid query parameter, $_REQUEST will not be empty and therefore not falsy and your validator will attempt to run but without the expected POST data (such as company_name).
If you're only wanting to validate POST data, you should only be inspecting $_POST.
See Gravy's answer for safer ways to check for the existence of array keys.
everyone! I've been having a terrible time trying to figure out why my form validation doesn't recognize empty fields and return them as errors.
Here is a function I use to check the fields:
function check_required_fields($required_array) {
$field_errors = array();
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
$field_errors[] = $fieldname;
}
}
return $field_errors;
}
Then, my form is process like this:
if (isset($_POST['submit'])) { // Form has been submitted.
$errors = array();
// perform validations on the form data
$required_fields = array('client', 'banner', 'district', 'store', 'position', 'first_name', 'last_name', 'email', 'password');
$errors = array_merge($errors, check_required_fields($required_fields, $_POST));
and an IF statement checks for errors:
if ( empty($errors) ) {
$query =
The problem is, even if my fields are empty (and I checked them with var_dump($_POST)) PHP performs the $query. I think there is something wrong with the function. I hope someone can help me spot the error!
Here is the gist of my HTML code:
<form action="registration.php" method="post">
<label for="first_name" class="medium">First Name</label>
<input type="text" name="first_name" class="textbox short_field">
<button type="submit" name="submit" value="submit" class="form-submit-button">SUBMIT</button>
</form>
I also use the following functions to validate string length and it works just fine:
function check_max_field_lengths($field_length_array) {
$field_errors = array();
foreach($field_length_array as $fieldname => $maxlength ) {
if (strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength) { $field_errors[] = $fieldname;
}
}
return $field_errors;
}
and
$fields_with_lengths = array('first_name' => 30, 'last_name' => 30, 'email' => 50, 'password' => 30);
$errors = array_merge($errors, check_max_field_lengths($fields_with_lengths, $_POST));
"The problem is, even if my fields are empty (and I checked them with var_dump($_POST)) PHP performs the $query."
Your problem is caused by this condition: $var != 0. Php can cast variables of different types between each other, so empty string is equal to 0. Proof:
<?php
$var = '';
var_dump($var == 0);
Output: bool(true)
Now look at this sample, imitating, how php processes your condition:
<?php
$var = '';
var_dump(empty($var));
var_dump((empty($var) && $var != 0));
Output:
bool(true)
bool(false)
In the 2-nd case the boolean function returns false, therefore, the variable won't be added to the array of errors.
I don't know, what do you want to achieve with this: $var != 0. But the condition:
if (!isset($_POST[$fieldname]) ||
(empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
$field_errors[] = $fieldname;
}
can be easily switched to this:
if (empty($_POST[$fieldname])) {
$field_errors[] = $fieldname;
}
I'm trying to validate my username as an email address, however PHP isn't letting me do this! what's wrong here?
//This checks if all the fields are filled or not
if (!empty($_POST['username']) ||
!empty($_POST['password']) ||
!empty($_POST['repassword']) ||
!empty($_POST['user_firstname']) ||
!empty($_POST['user_lastname']) ){
header('Location: register.php?msg=You didn\'t complete all of the required fields');
}
if (filter_var($_POST['username'], FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'The email address you entered is not valid';
}
here is the form i used in register.php
<form action="createuser.php" method="post" name="registration_form" id="registration_form">
<label>Email</label>
<input name="username" type="text" id="username" size="50" maxlength="50" /><br />
Typo?
header('Location: register.php?msg=You didn't complete all of the required fields');
^---unescaped embedded quote
Your empty logic is also faulty. You're checking if any fields are NOT empty (e.g. filled out) and then complaining that they're not filled out. remove the ! to invert the logic.
if (empty(...) || empty(...) || etc...)
instead of this use regular expression for validating your email address
function check_email_address($email) {
// First, we check that there's one # symbol,
// and that the lengths are right.
if (!preg_match("^[^#]{1,64}#[^#]{1,255}$", $email)) {
// Email invalid because wrong number of characters
// in one section or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if
(!preg_match("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&
↪'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
$local_array[$i])) {
return false;
}
}
// Check if domain is IP. If not,
// it should be valid domain name
if (!preg_match("^\[?[0-9\.]+\]?$", $email_array[1])) {
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if
(!preg_match("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|
↪([A-Za-z0-9]+))$",
$domain_array[$i])) {
return false;
}
}
}
return true;
}
and then check if it return true redirect it to location if not then simply throw an error
You would not get to Validate the email because your if statement is wrong .. it is checking if any of the post is not empty.
Replace it with
if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['repassword']) || empty($_POST['user_firstname']) || empty($_POST['user_lastname'])) {
For starters, look at the syntax highlighting for why you're getting parse errors.
header('Location: register.php?msg=You didn't complete all of the required fields');
needs to become:
header('Location: register.php?msg=You didn\'t complete all of the required fields');
How about you use javascript window.location? Sometimes header function is sensitive.And also put a submit button in your form since by default fields are empty when loaded.
if(isset($_POST['your_submit_button_name'])){
if (empty($_POST['username']) ||
empty($_POST['password']) ||
empty($_POST['repassword']) ||
empty($_POST['user_firstname']) ||
empty($_POST['user_lastname']) ){
?>
<script>
window.location = 'register.php?msg=You didn\'t complete all of the required fields';
</script>
<?php
}
if (filter_var($_POST['username'], FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'The email address you entered is not valid';
}
}
NOTE: I remove "!" before your empty function since youre trapping the fields that are empty.
Try to use this solution:
$FormData = $_POST;
if(isset($FormData['button_name'])){
$Errors = array();
foreach ($$FormData as $key => $value) {
if(empty($value)) $Errors[] = 'Some message';
if($key = 'username'){
if(filter_var($value, FILTER_VALIDATE_EMAIL){
$Errors[] = 'The email address you entered is not valid';
}
}
}
if(empty($Errors)){
// #todo Do some action
} else {
header('Location: register.php?msg=You didn\'t complete all of the required fields');
}
}
function check_email($check) {
$expression = "/^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/";
if (preg_match($expression, $check)) {
return true;
} else {
return false;
}
}
Now use this method as :
if(!check_email($_REQUEST['ContactEmail'])){
$register_error .="Enter the correct email address!<br />";
$reg_error=1;
}
When I sent an image to the code below, uploadImage.php, through a POST method, how do I add a String parameter?
<?php
$hasError = false;
foreach( $_FILES as $i=>$file )
{
if ( $file['error'] )
{
$hasError = true;
}
}
if ( ! $hasError )
{
$myFilePath = '_uploads/'.'_'.$file["name"];
$dta = file_get_contents($file['tmp_name']);
file_put_contents($myFilePath, $dta);
}
else
{
echo('Stick custom error message here');
}
?>
If I understand you correctly, add to the page from where the form is submitted an input:
<form ....>
...
<input type="text" name="my_key" value="default value" />
</form>
You can then access it from $_POST:
if (array_key_exists("my_key", $_POST) && !is_array($_POST["my_key"]))
echo htmlentities($_POST["my_key"]);
else
//error handling; field was not included or multiple values were given