I have some JSON parameters, that I want to validate if the value are empty with an IF statement. I have written an IF statement in a function to check, but the IF statement only checks for the parameter, I want to check for the values if they are empty. Please, how do I go about this.
my code
//api.php
$payment_type = $this->validateParameter('payment_type', $this->param['payment_type'], STRING, true);
$date_of_delivery = $this->validateParameter('date_of_delivery', $this->param['date_of_delivery'], STRING, true);
$your_generated_waybill_number = $this->validateParameter('your_generated_waybill_number', $this->param['your_generated_waybill_number'], STRING, true);
"payment_type" - is an example of parameter || "1" - is an example of value
{
"name":"create_insert_new_delivery",
"param":{
"payment_type":"1",
"date_of_delivery":"", //E.g here want to check if the value is empty
"your_generated_waybill_number":"39ei40909444567avaab",
}
}
//rest.php
public function validateParameter($fieldName, $value, $required = true){
if($required == true && empty($value) == true){
$this->throwError(EMPTY_PARAMETER, $fieldName . " parameter is missing"); //HERE check if the parameter is missing and fires error, but I also want to include value check
} else if ($required == true && empty($fieldName) == true){
$this->throwError(API_PARAM_REQUIRED, $fieldName . " value is required");
} else {
} //check when parameter is present but value is empty and leave if it is not required
}
testing your variable should be done by using the identity operator.
if (!$var){}
or
if ($var === null){} //checks by type
or
if (empty($field)){}
With empty() function you check for the value
$str = '';
// or
$str = null;
// or
$str = false;
var_dump(empty($str)) // output => true
To check if a variable is defined you can use isset
http://php.net/manual/ro/function.isset.php
You may make your function a little clearer since the tests you are doing will already return true or false. There is no need to compare them to true.
if ($required AND empty($value)) {
$this->throwError(EMPTY_PARAMETER, $fieldName . " parameter is missing"); //HERE check if the parameter is missing and fires error, but I also want to include value check
} elseif ($required AND empty($fieldName)) {
$this->throwError(API_PARAM_REQUIRED, $fieldName . " is required");
} elseif (!empty($fieldName) AND empty($value)) {
$this->throwError(API_PARAM_REQUIRED, $fieldName . " value is required");
}
}
You're main problem is that you're passing the value (grabbed from the array) to the method and checking that. Because at that point, if the array key is not set, a warning is triggered and the value is coerced to null.
empty(): Will return true when the variable is not set OR if it evaluates to some falsey value (e.g. false, null, [], "", etc)
isset(): Will return true ONLY if the value is not set.
So:
$a = ['one' => false];
empty($a['one']); //true
isset($a['one']); //true
isset($a['two']); //false
So you could edit you validation function like so:
public function validateParameter($fieldName, &$inputArray, $required = true){
if($required){
if(!isset($inputArray[$fieldName])){
$this->throwError(EMPTY_PARAMETER, $fieldName . " parameter is missing");
} else if (empty($inputArray[$fieldName])){
$this->throwError(API_PARAM_REQUIRED, $fieldName . " value is required");
}
} else {
if(!isset($inputArray[$fieldName])){
return null;
}
}
return $inputArray[$fieldName];
}
Note: since you are checking a class attribute $this->param. You may avoid passing the array to the method and just reference $this->param in the function, unless it should be more reusable.
I didn't completely understand you desired result in the missing block, but made a reasonable assumption
Related
Here is my sample code:
$issue_id = $_POST['issue_id'];
if(!empty($issue_id)){
echo 'true';
}
else{
echo 'false';
}
If I pass 0 to $_POST['issue_id'] by form submitting then it echo false. Which I want is: Condition will be true if the following conditions are fulfilled:
1. true when I pass any value having 0.
2. false when I don't pass any value. i.e: $_POST['issue_id'] is undefined.
I also tried this:
if(!isset($issue_id)){
echo 'true';
}
else{
echo 'false';
}
if(!empty($issue_id) || $issue==0){
echo 'true';
}
else{
echo 'false';
}
The last one is okay, meaning if I pass any value having ZERO then it will echo true. But it will also echo true if I don't pass any value. Any idea?
The last is okay, meaning if I pass any value having ZERO then it echo true. But it also echo true if I don't pass any value. Any idea?
if (isset($_POST["issue_id"]) && $_POST["issue_id"] !== "") {
}
please notice I used !== not !=. this is why:
0 == "" // true
0 === "" // false
See more at http://php.net/manual/en/language.operators.comparison.php
also if you are expecting number you can use
if (isset($_POST["issue_id"]) && is_numeric($_POST["issue_id"])) {
}
since is_numeric("") returns false
http://php.net/manual/en/function.is-numeric.php
Alternatively if you expect number good option is filter_var
if (isset($_POST["issue_id"]) {
$issue_id = filter_var($_POST["issue_id"], FILTER_VALIDATE_INT);
if ($issue_id !== false) {
}
}
since filter_var("", FILTER_VALIDATE_INT) will returns false and filter_var("0", FILTER_VALIDATE_INT) will return (int) 0
http://php.net/manual/en/function.filter-var.php
if(isset($_POST['issue_id'])) {
if($_POST['issue_id'] == 0) {
echo "true";
}
else {
echo "false";
}
}
When you get data from a form, remember:
All text boxes, whether input or textarea will come as strings. That includes empty text boxes, and text boxes which contain numbers.
All selected buttons will have a value, but buttons which are not selected will not be present at all. This includes radio buttons, check boxes and actual buttons.
This means that $_POST['issue_id'] will be the string '0', which is actually truthy.
If you need it to be an integer, use something like: $issue_id=intval($_POST['issue_id']);
#Abdus Sattar Bhuiyan you can also full fill your two condition like below one:
<?php
$_POST["issue_id"] = "0";
$issue_id = isset($_POST['issue_id']) ? (!empty($_POST['issue_id']) || $_POST['issue_id'] === 0 || $_POST['issue_id'] === "0") ? true : false : false;
if($issue_id){
echo 'true';
}
else{
echo 'false';
}
Why does myFunction() below validate the given parameter as true? This was caught by mistake as myFunction should normally receive the entire array as a parameter, but in this case only a specific value ("35") within the array was passed to the function. Yet, it still validated as true. What am I missing here as I would not expect the parameter to validate as true, it was passed a string, not an array?
$myVar = array('id' => '35');
myFunction($myVar['id']);
function myFunction($params) {
if (isset($params['id']) && !empty($params['id']) && $params['id'] == intval($params['id']) && $params['id'] > 0) {
echo "id is valid<br>";
echo "id = " . $params['id'] . "<br>";
echo "params = " . $params . "<br>";
print_r($params);
} else {
echo "id is invalid";
}
}
Output:
id is valid
id = 3
params = 35
35
You are not using strict comparison here $params['id'] == intval($params['id']) and PHP juggles with the types. Change it to $params['id'] === intval($params['id']).
Or use is_int() function.
I don't want to import blank/empty, space, null value on my database. So for this reason I want to check my input value before importing on database. Please any one can tell me isset and empty function which one is good for checking input value. here is my code. Thanks
$required = array('login', 'password', 'confirm', 'name', 'phone', 'email');
$error = false;
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
echo "All fields are required.";
} else {
echo "Proceed...";
}
In this situation empty makes more sense, because it also checks whether the string is empty. isset just checks whether if it is defined. You might also want to trim the input.
$required = array('login', 'password', 'confirm', 'name', 'phone', 'email');
$error = false;
foreach($required as $field) {
if (empty($_POST[$field]) || strlen(trim($_POST[$field])) == 0) {
$error = true;
}
}
if ($error) {
echo "All fields are required.";
} else {
echo "Proceed...";
}
isset is totally useless and empty is perhaps not an appropriate choice here.
The values inside $_POST (and also $_GET and $REQUEST) are always typed as strings, so isset will always return true. Additionally, the behavior of empty on false, null and other such values does not come into play, which means that the empty check will only reject:
zero-length strings
the string "0"
This is different from what your code seems to intend to reject, which would be:
zero-length strings
strings composed entirely of whitespace
Consider using trim($_POST['foo']) === '' as the condition instead.
The best way might be using empty and trim. Why trim? It will remove the spaces and lines etc. from the beginning and the end. That means, when someone inserts a few spaces but no text, the spaces can be removed so you can check empty:
if(empty(trim($foo)))
{
// It is empty!
}
Isset() checks if a variable has a value including ( Flase , 0 , or Empty string) , But not NULL.
Returns TRUE if var exists; FALSE otherwise.
empty() function checks if the variable has an empty value empty string , 0, NULL ,or False. Returns FALSE if var has a non-empty and non-zero value.
Example:
$var = 0;
// Evaluates to true because $var is empty
if (empty($var)) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if (isset($var)) {
echo '$var is set even though it is empty';
}
The source
In your case, you can use empty() function
Fix it:
foreach($required as $field)
{
$val = trim($_POST[$field];
if (empty($val))
{
$error = true;
}
}
You could incorporate isNotEmpty function
<?php
function isNotEmpty($input){
$strTemp = trim($input);
if($strTemp !== ''){
return true;
}
return false;
}
?>
Save isNotEmpty as 'isnotempty.php' encase you need to reference it in the future.
include 'isnotempty.php';
$error = false;
foreach($required as $field) {
if (!(isNotEmpty($_POST[$field]))) {
$error = true;
}
if ($error) {
echo "All fields are required.";
} else {
echo "Proceed...";
}
Hope this helps
I'm trying to make an if statement with 2 conditions. One that checks if one variable is NOT present & does NOT matches the word "good2go" and the other that checks to make sure "body" variable is present. I'm trying to trip the error message here. Here is what I have and what I've tried, and none of it seems to work.
if (stripos($_POST['check'], 'good2go') == FALSE && $_POST['body']) {
$error = true; }
if (!$_POST['check'] == 'good2go' && $_POST['body']) {
$error = true; }
if (!stripos($_POST['check'], 'good2go') && $_POST['body']) {
$error = true; }
if ((!stripos($_POST['check'], 'good2go')) && $_POST['body']) {
$error = true; }
How do I get this to work?
here's the entire code of contact_us.php this has the validation code and the email code.
$error = false;
if (isset($_GET['action']) && ($_GET['action'] == 'send')) {
// Winnie the pooh check
//$t = tep_db_prepare_input($_POST['verify']);
if (!isset($_POST['check']) && !$_POST['check']=='good2go' && isset($_POST['body'])) {
$error = true;
} else { // Winnie the pooh Check
$name = tep_db_prepare_input($_POST['name']);
$email_address = tep_db_prepare_input($_POST['email']);
//IP recorder start
$ipaddress = $_SERVER["REMOTE_ADDR"];
$ip = "\n\nIP: " . $ipaddress;
$content = "\n\nName: ".$name."\n\nComments: ".$_POST['enquiry'];
$product = tep_db_prepare_input($_POST['product']);
if ($product) {
$product_text = "\n\nProduct Interest: ".$product; }
$content_ip = $content . $product_text. $ip;
$enquiry = tep_db_prepare_input($content_ip);
//IP recorder end
}
// BOF: Remove blank emails
// if (tep_validate_email($email_address)) {
// tep_mail(STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, EMAIL_SUBJECT, $enquiry, $name, $email_address);
// tep_redirect(tep_href_link(FILENAME_CONTACT_US, 'action=success'));
// } else {
// $error = true;
// $messageStack->add('contact', ENTRY_EMAIL_ADDRESS_CHECK_ERROR);
if (! tep_validate_email($email_address)) {
$error = true;
$messageStack->add('contact', ENTRY_EMAIL_ADDRESS_CHECK_ERROR);
}
if ($enquiry == '') {
$error = true;
$messageStack->add('contact', ENTRY_EMAIL_CONTENT_CHECK_ERROR);
}
if ($error == false) {
tep_mail(STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, EMAIL_SUBJECT, $enquiry, $name, $email_address);
tep_redirect(tep_href_link(FILENAME_CONTACT_US, 'action=success'));
// EOF: Remove blank emails
}
}
Solution to your updated problem:
if (!isset($_POST['check']) || !$_POST['check']=='good2go' || !isset($_POST['body'])) {
$error = true;
}
The reason for the pipes vs ampersands is that you want to throw an error if ANY of the fields has issue. Also, you want to check if body is NOT set vs IS set. Glad this worked out for you!
and the other that checks to make sure "body" variable is not present.
if(stripos($_POST['check'], "good2go") !== false && !isset($_POST['body'])){
//code here
}
According to PHP docs regarding the stripos function:
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
So you need to change the first line to:
// Doing stripos checks you MUST use === (not ==)
if (stripos($_POST['check'], 'good2go') !== FALSE && $_POST['body']) {
$error = true; }
And to check if there is no $_POST['body'] you can change the above to:
if (stripos($_POST['check'], 'good2go') !== FALSE && (!isset($_POST['body'])) {
-- Update --
According to your comment, you need $_POST['check'] to equal 'good2go', then you shouldn't be using stripos as it will check for the existence of good2go regardless if it's exactly equal, or part of a string; 'wow this hamburger is good2go'.
So I would change the conditional to:
if (((isset($_POST['body'])) && (strlen($_POST['body']) > 0)) && ((!isset($_POST['check'])) || ($_POST['check'] !== 'good2go'))) {
// Post body has a value and Post check DOES NOT equal good2go, someone is hax0rin!
}
You may want to read up on Cross-site request forgery as it seems right inline with what you are working on.
One that checks if one variable is present & matches the word "good2go"
isset($_POST['check']) AND $_POST['check'] == 'good2go'
and the other that checks to make sure "body" variable is not present.
!isset($_POST['body'])
so, just put them together
if (isset($_POST['check']) AND $_POST['check'] == 'good2go' AND !isset($_POST['body'])) {
$error = true;
}
try this:
if(!empty($_POST['check']) && $_POST['check']=='good2go' && empty($_POST['body'])) { $error=true; }
Consider using empty instead of isset if your $_POST['body'] can be present with an empty value.
No need for all those unneeded functions. What you are trying to achieve is:
if (isset($_POST['check']) && $_POST['check']=='good2go' && !isset($_POST['body']) {
// your code
}
However, As per the title of the question: Use a ternary statement. Syntax is as such
$var = <condition> ? <true> : <false>;
I have this function that will check if a user already exists in the DB or not:
function checkTwitterAccount($user_id) {
$accountExists = false;
$a = "SELECT * FROM twitterAccounts WHERE user_id='".$user_id."'";
$ar=mysql_query($a) or die("Error selecting twitter account: ".mysql_error());
$ac = mysql_num_rows($ar);
if ($ac > 0) {
$accountExists = true;
}
return $accountExists;
}
Now when I call this function how do I actually know if the user is or is not in the DB?
I mean how do I call this function and how do I check the result?
Is the below right?
If (checkTwitterAccount($user_id) = true) {
DO THIS
}else{
DO THAT
}
Please help me I am new to it.
Thanks
if (checkTwitterAccount($user_id)) { //true
//do something
} else { //false
//do something
}
if (checkTwitterAccount($user_id) == true) {
//do this
}
else {
//do that
}
You have to use == rather than = as the = operand sets the value to true in the code you wrote, whereas the == operand compares the returned value to true.
Since your returning a true or false value you can simply use:
If (checkTwitterAccount($user_id)) {
//DO THIS
}else{
//DO THAT
}
Note: that your original line:
If (checkTwitterAccount($user_id) = true) {
would result in an assignment error because a single "=" means assign a value which can't be done to a function. You wanted:
If (checkTwitterAccount($user_id) == true) {
because "==" compares a value. Further, == only compares the value so for example 0 is the compares positively with false, any number compares positively with true, if you want to also compare type you us "===" like this:
0 == false //true
0 === false //false
false == false //true
false === false //true
1 == true //true
1 === true //false
true == true //true
true === true //true
function checkTwitterAccount($user_id) {
$user_id = intval($user_id);
$a = "SELECT `user_id` FROM `twitterAccounts` WHERE `user_id` = '".mysql_real_escape_string($user_id)."'";
$ar = mysql_query($a) or die("Error selecting twitter account: ".mysql_error());
$ac = mysql_num_rows($ar);
return ($ac > 0);
}
if(checkTwitterAccount($someid)) {
// Exists...
} else {
// No such ID in the DB
}
Note that comparison operator is == not = (which is assign).
So you could do:
if(checkTwitterAccount($someid) == true) {
However, it isn't necessary here.
Also remember to sanitize the data in the query.
if (checkTwitterAccount($user_id) == true){
do something if its true
} else {
do something if its flase
}
should work.. given that you provide argument to that function which seems to be
the int.. or id number from id column from users table in the db.
Basically you have a HTML Form that takes in a username and checks the database
for that users id number in users table in the database. Once it has this number it will
pass it on to the function checkTwitterAccount($user_id) if that function returns True that means guessing by the name of the function that the user has a twitter account else he does not have one.
you could do:
if (checkTwitterAccount($user_id) == true){
echo "This user has a twitter account";
} else {
echo "This user does not have a twitter account";
}
You can shorten the orig. function.
function checkTwitterAccount($user_id) {
$a = "SELECT * FROM twitterAccounts WHERE user_id='" . $user_id . "'";
$ar = mysql_query($a) or die("Error selecting twitter account: " . mysql_error());
return mysql_num_rows($ar) > 0; // boolean (will be true or false)
}
Then use the answer from max_. (See comparison operators)