php,symfony 2 filter case sensitive - php

I want to ignore case in a filter , My code:
if (strtolower(isset($filterObject['name'])) && null !== strtolower(($filterObject['name']))) {
$queryFilter->addStringFilter("name", ($filterObject['name']));
}

If you want to ignore the casesensitivity of the addStringFilter by lowercasing the object
you would just have to use strtolower($filterObject['name']).
strtolower lowercases the string given.
On that note you are using strtolower on an isset function result which won't do a thing there (as isset returns no string).
So you should change your sourcecode to:
if (isset($filterObject['name']) && null !== strtolower(($filterObject['name'])))
{
$queryFilter->addStringFilter("name", strtolower(($filterObject['name'])));
}
Btw one case you didn't check is if $filterObject['name'] is empty (not sure if it is possible as I don't know your remaining code. If it CAN be possible you want to add another and into the if:
&& $filterObject['name']
That would make sure that it is filled with more than an empty string.
Thus the if part would change to:
if (isset($filterObject['name']) && $filterObject['name'] && null !== strtolower(($filterObject['name'])))

Related

PHP Is one value set and not another

I'm working on a truthy/falsy where I need to check 2 values, of which one may be null, the other 0. If integer vs string value same, they'd be the same.
The simplest I've been able to break it down is:
if($var1 == $var2) {// They may be the same
if((isset($var1) && !isset($var2)) || (!isset($var1) && isset($var2))) { // Is one set, and not the other?
return true; // As different as we'll allow
}
return false; // Nope they're the same
}
return true; // Definitely different
My question would be mainly, given the above code block, is there a simpler way to check if one value is set, and not the other?
EDIT: The reason I check for equality first, is that the value may pass 1 == 10 or 10 == '10', in which case, I don't need to check further, but if null == 0, this would pass and require further checking. I saw that I can pass multiple values to isset, which would work if I required both to be set or both not set, but if one is, and not the other, that's where I need to flag.
Using the null coalescing operator may come in handy...
return ($var1 ?? null) !== ($var2 ?? null);
Checks that they are not equal and at least one is defined and not null.
You are checking for equality before checking if they are set.
I'd recommend checking if they are set first.
If the PURE goal is to check if one is set and not the other, then:
return ( ( empty($var1) && ! empty($var2) ) || ( ! empty($var1) && empty($var2) );
Per comments, isset is the requirement, so this version:
return ( ( isset($var1) && ! isset($var2) ) || ( ! isset($var1) && isset($var2) );
And, props to #deceze to suggest an even simpler version:
return ( isset($var1) != isset($var2) );

PHP: Validation for required field

I want to validate a field which is required. I am using following condition to check whether the field is not empty:
isset($value) && !empty($value)
But if I write 0 in the fields, it will still say the field is required. The empty() function considers 0 as an empty value as told in PHP manual but what else should I do? I have tried writing many conditions but they didn't work as expected.
I saw user contributions and found:
empty($var) && !is_bool($var)
I tried adding it to my condition like this but didn't work:
isset($value) && !empty($value) && is_bool($value)
Try below code:
$value = 0;
if(isset($value) && $value !== "")
{
echo "Field not required";
}
else
{
echo "Field required";
}
Output:
Field not required
Demo:
http://3v4l.org/JWJbj
Explanation:
The integer 0 is truthy. It means that anything that checks it in a boolean'ish manner will treat it as false. In particular, !empty($value) will evaluate to false, so is_numeric would never even get a chance to fail.
Short version: empty is too wishy-washy in this case. Check for null and '' explicitly (with data-type hence used !==).
You can't check for empty. Basically you can only stick to the isset test.
If a field in the form was not filled this variable field will not be inside the $_POST superglobal and isset will return false. If the user typed 0 the variable name will exist inside $_POST isset will return true.
I would do it as following:
function emptyTextValue($value)
{
return trim((string) $value) !== '';
}
You know that all you get is a string, so you don't need full functionality of empty() function:
isset($_POST['yourFieldName']) && $_POST['yourFieldName'] !== ''
You can replace the empty function by :
$value !== ""
If it's not exactly empty, then it will validate the condition.
What I've done for my test is convert the empty check to a strlen check. Because PHP is so friendly, you can run a string comparison on the value. A value of null will return a 0 length string, while a value of 0 will return a length of 1. So what I've done is this:
if(isset($val) && strlen($val) > 0){
// Do stuff
}
Try
isset($value) && $value != ''
I have found a nice condition by myself.
$value === 0 || $value === "0" ? isset($value) : isset($value) && !empty($value)
This works perfectly for every case.
I would check to be sure that the form had been submitted and then trim the field 'msg' in case there were any white space chars, i.e. newlines, carriage returns, tabs, spaces and then test that result to make sure it's not the empty string as follows:
<?php
if ( isset($_POST['msg']) && trim($_POST['msg']) !== '') {
// other code
}

Why do I have to check "IF" ($_GET["$view"]) && $_GET("$view")! . What does "!" mean? Why does it equal = ""

I can't understand that if sentence. Why can't I just check if $view is set? 2 more questions -What does "$_GET("$view")!" "!" sign mean there? What does ! change? Moreover, why does it equal = " "?
<?php
$myurl=htmlspecialchars($_SERVER["PHP_SELF"]);
$view="";
if(isset($_GET["$view"]) && $_GET("$view")! = "") { $view =$_GET["$view"];};
include(head.html);
switch($view] {
case "" :
include(main.html);
break;
case "people" :
include(people.html);
break;
case:"contact":
include(contact.html);
break;
default :
include(404.html);
break;
};
include_once(foot.html;
?>
Thanks for all the help
I think you messed up your code. This will not execute, due to numerous errors. The if statement is probably
if(isset($_GET[$view]) && $_GET[$view] != "")
Ie, first check that the $view key exists, then check that key it is not empty. Note the difference between a key that does not exist, and a key that exist but is empty, and why you check for both in this case.
Why can't I just check if $view is set?
Because apparently the author of that code didn't want the empty string to be valid. This will be the case if, say, there is a field called $view and the user does not put anything in it.
Actually, you could do that, since $view is initialized to the empty string anyway! This code was probably copy/pasted or written by a novice.
What does ! change?
It's actually !=, written in a confusing way. These two are the same:
&& $_GET("$view")! = "")
&& $_GET("$view") != "")
Also, your code has a bug. $_GET("$view") is not valid, the () should be []. So, here is the corrected and readable code:
if (isset($_GET["$view"]) && $_GET["$view"] != "") {
$view = $_GET["$view"];
}
Also:
switch($view] // ...what is this?
include_once(foot.html; // and this?
case:"contact": // ummmm
$view="";
if(isset($_GET["$view"]) && $_GET("$view")! = "") { $view =$_GET["$view"];};
You actually set $view=""; as an empty parameter
There for isset($_GET["$view"] looks like this isset($_GET[""]
You whole if statement with the above code is ignored
Likewise your switch($view); also looks like switch("")
This means only your first case will be executed no matter what you have in your $_GET
Check this portion of your code too for errors. the colon after case needs to be removed
case:"contact":
include(contact.html);
break;
For first, use correctly [] and (). Then you have to learn about operators: http://www.w3schools.com/php/php_operators.asp
For now your code is non-sense.

empty and zero as a string

How do I write an if condition that will evaluate a zero as not empty? I'm writing a validation script and if the field is blank, I throw an error. In the case of a select with numerical values that start with 0 (zero), that should not considered to be empty. The manual states that a string 0 is considered to be empty and returns false. If I change empty to !isset, the zero works but the other textboxes that are truly empty pass validation. How do I write this to handle my case?
if (strlen($x)) {
// win \o/ (not empty)
}
Happy coding.
(All text box / form input content is inherently just text. Any meaning as a numerical value comes later and each representation can be validated. 0 is coerced back to "0" in strlen.)
Have you considered using is_null()?
if (is_null($value) || $value === "") {}
if (empty($value) && $value !== 0)
if(!is_numeric($var) && empty($var))
{
// empty
}
else
{
// not empty
}

!is_null() not working as expected

dispatch_address_postcode
isn't mandatory and it will still run even if it's blank:
if (!is_null($_POST['personal_info_first_name']) &&
!is_null($_POST['personal_info_surname']) &&
!is_null($_POST['personal_info_email']) &&
!is_null($_POST['personal_info_telephone']) &&
!is_null($_POST['dispatch_address_country']) &&
!is_null($_POST['dispatch_address_first_name']) &&
!is_null($_POST['dispatch_address_surname']) &&
!is_null($_POST['dispatch_address_address']) &&
!is_null($_POST['dispatch_address_town']) &&
!is_null($_POST['dispatch_address_postcode']) &&
!is_null($_POST['dispatch_address_county']) &&
( ($_POST['payment_method'] == "Pay by credit card.") ||
(
($_POST['payment_method'] == "Pay by new credit card.") &&
!is_null($_POST['card_number']) &&
!is_null($_POST['expiration_date']) &&
!is_null($_POST['security_code'])
)
)
)
What gives?
"dispatch_address_postcode isn't mandatory and it will still run even if it's blankā€¦"
Just look at that sentence again. If the field is not mandatory, it is perfectly okay if the code runs if the field is blank. If a field isn't mandatory, don't test it as mandatory.
The real problem is though, is_null only tests if the variable is null. POSTed values will never be null, if they're empty they will be '' (an empty string). All your !is_null tests will always be true, and you will get a warning if the variable isn't set (something you don't want to happen). The more appropriate test would be !empty.
Even more appropriate tests would include a test if the value appears to be valid (does email look like an email address, does telephone have at least x digits in it?). You should also loop through the fields to make your code more readable, endless nested and chained if conditions are no joy to look at.
$mandatoryFields = array('foo' => 'email', 'bar' => 'telephone');
foreach ($mandatoryFields as $field => $rule) {
if (empty($_POST[$field]) || !validateByRule($_POST[$field], $rule)) {
raiseHell();
}
}
It looks like you're trying to make sure all post variables are submitted. Would you like help with that?
Using !empty() may not be the answer to your specific question, but it would definitely help with what it looks like you're trying to do.
empty() returns TRUE if the $_POST key isn't set, if its an empty array, or even if its an empty string, so using !empty() is a good way to make sure that the user has filled in the information.
Try writing your own is_valid function and use that rather than is_null.
For example (and this is by no means comprehensive):
function is_valid(&$array, $key, $required=false) {
if(!array_key_exists($array))
return false;
$value = trim($array[$key]);
if(empty($value) && $required)
return false;
return true;
}
Use like so:
if(is_valid($_POST, 'personal_info_first_name', true) && ...)
!is_null($_POST['personal_info_first_name']) && !isset($_POST['personal_info_first_name'])
use array_key_exists('card_number', $_POST) && !empty($_POST['card_number'])
Edit: Please consider this before a downvote. I'm leaving this here to serve as a "what not to do". I would delete it because it's bad, but then nobody would learn from my mistakes.
DO NOT DO THIS - read the comments for great info on why this is bad
My answer is going to be wildly different, but I am a wildly different guy...
I JUST found that this will work. Instead of all that isset and things, just assign the variables programmatically! I think I have some refactoring to do... y'know on all my code...
if (!is_array($_POST)){exit "$_POST isn't an array";}
foreach ($_POST as $param => $value){
${$param} = secure($value);
}
//now you have a set of variables that are named exactly as the posted param
//for example, $_POST['personal_info_first_name'] == $personal_info_first_name
if ($payment_method == "Pay by credit card."){
//do stuff that you were gonna do anyways
} else if ($payment_method == "Pay by new credit card.") {
if ($card_number && $expiration_date && $security_code){
//do stuff that you were gonna do anyways
} else {
exit("info missing for credit card transaction");
}
} else {
exit("unknown payment method")
}
function secure($input){
//sanitize user input
}
If you use this code, then it doesn't matter what is null and what isn't within the foreach because anything that's null just won't be made. Then you can use nicer looking code (and probably faster code) to check for anything that is required.

Categories