Trimming my inputs before validating? - php

I have some questions about my server-side validation script.Currently, i validate my input data by checking if the fields in the $_POST array are empty, of if they are shorter than the min length.
My script(extract);
if(!isset($_POST['BizAddItemCat']) OR empty($_POST['BizAddItemCat']))
{
die("Please enter a category for your item.");
}
if(!isset($_POST['BizAddItemSubCat']) OR empty($_POST['BizAddItemSubCat']))
{
die("Please enter a subcategory for your item");
}
if(!isset($_POST['BizAddItemName']) OR empty($_POST['BizAddItemName']) OR strlen($_POST['BizAddItemName']) < 5)
{
die("Your item name must contain at least 5 characters");
}
if(!isset($_POST['BizAddItemPrice']) OR empty($_POST['BizAddItemPrice']))
{
die("Your item must have a price");
}
if(!isset($_POST['BizAddItemQty']) OR empty($_POST['BizAddItemQty']))
{
die("You must enter your available stock for your item");
}
if(!isset($_POST['BizAddItemDesc']) OR empty($_POST['BizAddItemDesc']) OR strlen($_POST['BizAddItemDesc']) < 20)
{
die("Your item description must contain at least 20 characters");
}
I then trim the $_POST variables and assign them to variables
$itemcat=trim($_POST['BizAddItemCat']);
$itemsubcat=trim($_POST['BizAddItemSubCat']);
$itemname=trim($_POST['BizAddItemName']);
$itemprice=trim($_POST['BizAddItemPrice']);
$itemqty=trim($_POST['BizAddItemQty']);
$itemdesc=trim($_POST['BizAddItemDesc']);
However, a string with all spaces (e.g " " ), will pass the empty() check but all the spaces will be removed by trim(). Therefore if i have a string with all spaces passed in, it would pass my validation and will have all the spaces removed, leaving me with an empty variable?
However, if i trim my variables before validating them, then i wouldn't be able to check if the fields exist (isset($_POST['etc'])?
If so, how would i go about addressing this?

You could either trim the value before it goes through the condition, or, change the condition to check for an empty string.
if ($_POST['whatevervalue'] !== " ")
I would suggest going with trimming before the condition. Although why you're assignment statements come after the checks is confusing me.

Related

How to validate an empty search string

I'm trying to do a search with multiple keywords. For testing purposes ,the search string looks like this
http://localhost/admin/search.php?search=live+concert
So far, the search works perfectly!!!
If there is no parameters, im able to echo a message
if (isset($_GET['search'])) {
// split keywords
$keywords = preg_split('/[\s]+/', $_GET['search']);
// search
} else {
echo 'Nothing to search';
}
Here's my problem. When I hit the search button without entering keywords, i get an empty string , like this
http://localhost/admin/search.php?search=
I want to echo an error to the user saying that there is no keywords to search for. I've tried using count($keywords), but i always get 1 as a result when no keywords have been entered.
How do i check if the user hit the search button without entering keyword(s) ?
Thanks
You can use trim($_GET['search']) where you remove any additional spaces and check if then $_GET['search'] is not '' this way even if the user only submits space, your error message shows
if (isset($_GET['search']) && trim($_GET['search']) != '') {
You might be able try something like this:
if (empty($_GET['search'])) {
echo 'You did not enter anything';
}
empty checks to see if the var is either 0, empty, or not set at all. Not that this matters but as of PHP 5.5 empty() supports expressions, rather than only variables.
You can use simple validation as below, this will check if "search" is posted and its not NULL or not having a while space and length is greater than 0
if (isset($_GET['search']) && strlen(trim($_GET['search']))>0) {
// do the search
}else{
echo 'Nothing to search';
}
If the user has clicked the search button, $_GET['search'] will be set but empty, which is why your 'isset' condition is failing. Why not a simple:
if (!trim($_GET['search'])){ //trim removes whitespace from beginning and end
The empty function should work -
if ( isset($_GET['search']) && !empty(trim($_GET['search'])) )
You can use if ($_GET['search'] == '') {/*ERROR*/} or if (strlen($_GET['search']) < 1) {/*ERROR*/}.
These could also be added to your already existing if statement.
The problem with using count is that when you place an empty string as the second argument for preg_split(), an array with one empty string value will be returned: array(''). Therefore, the amount of values in the array will be one.

Understanding XOR PHP

I am writing section in my program to update a user, and there is password and confirm passwords. I dont want to do anything to the password field in the DB unless they have filled the fields in.
So I have error checking for:
if(($sql['password']!="") && ($sql['cpassword']!=""))
{
if($sql['password'] == $sql['cpassword'])
{
//update
}
}
However I want to write a quick line to throw an error message if they only filled out one of the password fields. So I figured:
if($sql['password'] ^ $sql['cpassword'])
{
echo You must fill out <i>both</i> password fields and they <i>must</i> match.";
}
Would do it, but It doesnt seem to. Then I added a NOT operator, !, and that seemed to work well, however if both fields have nothing in them, I still get the error message :(
From the logic I can see from this answer, It would seem that simple XOR would work. But
But it doesnt, Can someone explain to me why?
XOR certainly is not what you want here.
As David states, XOR will return a "true" result if the values are different, however when you XOR two strings the XOR operation is only done up to the point of the shortest string.
Examples
'AAAA' ^ 'AAAA' This returns an empty string (false-equivalent value) as the values are the same.
'AAAA' ^ 'bbbb' This returns an non-empty string (true-equivalent value)..
'AAAA' ^ 'AAAAbbbb' This returns an empty string (false-equivalent value), even though the strings are different. This is because the result of the operation only considers the first 4 characters.
In Sandy Lee's example (bool)$string does not really help.
(bool)'0' = false
(bool)'1' = true
This does not tell you if the string is empty or not. It simply gives you the boolean-equivalent value of the string.
There is no need to use XOR here at all. It's not the right tool for the job. There is no need to try and do anything fancy either, the simple tools work perfectly.
$password = trim($password);
$confirm = trim($confirm);
if (!$password || !$confirm) {
// One of the fields was not completed.
}
elseif ($password !== $confirm) {
// Fields did not match
}
else {
// Update password
}

PHP checking if empty fields

I have a sign up form with about 10 fields and they are all required to be filled in before processing, so trying to avoid all those if checks I came up with this, is this a good method?
foreach($list as $items) {
if(empty($items)) {
$error[] = "All fields are required.";
break;
}
}
or should I make if(empty($field_1) || empty($field_2) etc.. then output the error?
Assuming that your data is coming from $_GET or $_POST, all data fields will be strings. This means that you should be able to do the check in a single function call:
if (in_array('', $list, TRUE)) {
$error[] = "All fields are required.";
}
This looks for strings which are exactly equal to an empty string. If you want to make the comparisons loose (more or less identical to the check that empty() does) just remove the final TRUE.
EDIT Thinking about it, you don't need the strict comparison. I did this to allow for a legitimate field value of '0' (which empty() would not allow) but this will also be permitted with loose comparisons, since '0' != ''.
ANOTHER EDIT If you want to check that the length of the sting is greater than two, you will have to loop:
foreach ($list as $item) {
if (strlen($item) < 2) {
$error[] = "All fields are required.";
break;
}
}
This will also "clear out 0" assuming that by this you mean "not allow a value to be 0". If you also want to disallow '00' (or any other string that results in 0) you can change the if clause to this:
if (strlen($item) < 2 || (!(int) $item)) {
it's ok. If you just want to show message "All fields are required." without showing which field in blank.
Otherwise it will be more user friendly if you check and show which field is left empty.
It's good idea to put it into loop as you did but please note that this will fail even when user inputs 0 and will pass for string containing only spaces, so you may want to make better checks than empty()
I would approach this with an in_array check.
<?php
$fields=array('name','age','yadayada','something_else');
foreach ($_POST as $key=>$value){
if(in_array($key,$fields) && $value!=''){
$$key=$value;
}else{
$error[$key]='This field is required.';
}
}
?>

Determine if variable has ANY text

I would like to determine whether or not a variable has any text at all.
For instance, my current code is this:
if (is_numeric ($id))
{
//do stuff
}
else
{
// do other stuff
}
However, there is a problem if my variable contains both a string and a number
such as "you are 93 years old",
because it sees that number 93 is present and considers the variable numeric.
I want the if statement to only "do stuff" if there is absolutely no text in the variable at all.
Thanks
Try casting the value to int (or float) then compare it back to the unaltered version. They should match values (but not type)
if((int)$id == $id) {
} else {
}
another option would be to use preg_match("/^([\d.\-]+)$/", $id). This would allow you to be very specific about what characters you let $id contain. However using regexp should be considered as the final choice (for performance reasons)
if(empty($var) && $var !== "0" && $var !== 0) {
// it's really empty, not a string "0" and not a numeric 0
}
You could also check if it's not a boolean false for the sake of completeness.

PHP Logic - Return False of one or two out of three are not set

I have a form that collects information, one piece of which is a phone number. The phone number data comes from three fields, one for an area code, for the first 3 digits, and for the last four, so that numbers are in this format: xxx-xxx-xxxx (basic U.S. format).
These three fields are not required, but I would like to do some basic error checking if someone decides to fill out any combination of the three field:
(let's say they only give me the area code - that means that they wanted to give me their number, so in essence, it becomes required, so the code should check to see that 1) all three data sets were sent, and 2) all three are only numbers)
Here is what I thought would work, but it does not:
if((isset($_POST['numArea'], $_POST['numFirst'], $_POST['numSecond']) && (!ctype_digit(trim($_POST['numArea'])) || !ctype_digit(trim($_POST['numFirst'])) || !ctype_digit(trim($_POST['numSecond'])) || strlen(trim($_POST['numArea'])) !== 3 || strlen(trim($_POST['numFirst'])) !== 3 || strlen(trim($_POST['numSecond'])) !== 4))
|| (isset($_POST['numArea']) XOR isset($_POST['numFirst']) XOR isset($_POST['numArea']))){
$errors[] = 'Please give us a valid Phone Number, or remove any numbers if you do not wish to use your phone number.';
}else{
$_POST['PhoneNumber'] = '+01'.$_POST['numArea'].'-'.$_POST['numFirst'].'-'.$_POST['numSecond']; }
Any suggestions?
The reason why your code isn't working is not because of your boolean logic, but because of your use of isset(). In the case of a <input type="text">, the $_POST['fieldName'] will always be set, regardless of if the value is empty or not.
Use $_POST['fieldName'] != '' instead to determine if the user has entered a value. DO NOT USE empty(), as this will return any falsy value as empty (0, 000, false, etc...).
Personally, I rather use one <input type="type"> for the phone number. This is less annoying than making the user switch boxes, and also makes validation simpler.
This example actually validates if the number follows NANP rules. I find it absolutely ridiculous that so many applications/websites oversees this validation step.
// Did the user post a number?
if($_POST['phone'] != '') {
// Get only the numbers, we don't care how the user formatted their number
$_POST['phone'] = preg_replace('/[^0-9]/', '', $_POST['phone']);
// Is it a valid NANP phone number?
if(preg_match('/^1?[2-9][0-8][0-9][2-9][0-9]{6}$/i', $_POST['phone']) === 1) {
echo "Valid NANP phone number";
// Trim the leading one
$_POST['phone'] = ltrim($_POST['phone'], '1');
// Format as wanted
$_POST['PhoneNumber'] = '+01'.substr($_POST['phone'],0,3).'-'.substr($_POST['phone'],3,3).'-'.substr($_POST['phone'],6,4);
} else {
echo "Invalid phone number";
}
} else {
echo "User didn't provide phone number";
}
First of all if those fields are inputs then isset() will always return true. What you probably want to check is if they are not empty. So you should use empty() function for that.
I will replace your form values with $a, $b and $c to make it simple.
$a = $_POST['numArea'];
$b = $_POST['numFirst'];
$c = $_POST['numSecond'];
if (!empty($a) || !empty($b) || !empty($b)) {
// we know now that at least field was filled in, lets check their values
$regex = '/^\d+$/';
if (!preg_match($regex, $a) || !preg_match($regex, $b) || !preg_match($regex, $c)) {
echo "Phone number invalid";
}
}
This is just an example. You could shorten it to just one if statement but I haven't done so to make it more readable.
Just check if one of the fields is not set;
if (!isset($_REQUEST['numFirst']) || !isset($_REQUEST['numSecond']) || !isset($_REQUEST['numArea'])) {
if (!isset($_REQUEST['numFirst'])) {
print 'Please fill out the FIrst area';
}
if (!isset($_REQUEST['numSecond'])) {
print 'Please fill out the Second area';
}
if (!isset($_REQUEST['numArea'])) {
print 'Please fill out the Area code';
}
}
Is that the kind of thing you wanted to do?
This is not solution for your problem , but it will solve it other-way , try imask
it's actually a JS script .
Well first off, if anyone is ever gonna be able to maintain your code, you'll have to break that up into method calls. I'd probably write it something like this:
public function phoneNumberWasProvided () {
return !(empty($_POST['numArea']) &&
empty($_POST['numFirst']) &&
empty($_POST['numSecond']));
}
public function phoneNumberIsValid () {
$this->_phoneErrors = array();
// The following three if statements can also be
// extracted into their own methods
if(!preg_match("/^\d{3}/$", $_POST['numArea']) {
$this->_phoneErrors['numArea'] = 'The area code you provided is invalid';
}
if(!preg_match("/^\d{3}/$", $_POST['numFirst']) {
$this->_phoneErrors['numFirst'] = 'The first part of the provided phone
number is invalid';
}
if(!preg_match("/^\d{4}/$",$_POST['numSecond']) {
$this->_phoneErrors['numArea'] = 'The first part of the provided phone
number is invalid';
}
return empty($this->_phoneErrors);
}
Now you can easily use these methods inside your main logic, making it more readable:
if($this->phoneNumberWasProvided()) {
if(!$this->phoneNumberIsValid()) {
$errors = $this->getPhoneNumberErrors();
// Print errors / do whatever is necessary
} else {
$phoneNumber =
"{$_POST['numArea']}-{$_POST['numFirst']}-{$_POST['numSecond']}";
}
}

Categories