PHP return the value but false - php

I have this simple function:
function isMember($uID, $pdo) {
$status = getUserStatus($uID, $pdo);
if(isAllowed($status['status']))
return $status['status'];
return false;
}
Now I am looking for a way to return false yes, but to return also the value of the variable.
I tried the following, but it makes it empty anyway:
return $status['status'] == false;
So the logi is return false anyway but give me back also the value of the variable, even if it's false, because false should not mean empty :)

Return an array, and use the list() method to get your results:
function isMember($uID, $pdo) {
$status = getUserStatus($uID, $pdo);
$statusString = $status['status'];
$statusFlag = false;
if(isAllowed($status['status']))
$statusFlag = true;
return array($statusFlag,statusString);
}
//usage
list($flag,$msg) = isMember(5,"whatever");
echo "Access: $flag, with message $msg";

A function can not return multiple values, but similar results can be obtained by (1) returning an array or by (2) passing a variable by reference and storing the value you want returned in that variable.
You will need to write your function in a way that it returns an array containing the following:
The value you wan't returned
A flag that signifies true/false
Pass a variable by reference into your function and store the value of the status in that variable.
function isMember($uID, $pdo, &statByRef) {
$status = getUserStatus($uID, $pdo);
if(isAllowed($status['status'])) {
return $status['status'];
}
$statByRef = $status['status'];
return false;
}

False returns empty in PHP, see http://php.net/manual/en/function.empty.php
From documentation:
Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.

Try using something like this:
function isMember($uID, $pdo) {
$status = getUserStatus($uID, $pdo);
if(isAllowed($status['status'])){
return $status['status'];
}
return false;
} // If isAllowed returns true, then PHP will return $Status['Status'];, if not then PHP will by default return false.
I have noticed you haven't used braces which makes the code a little awkward to debug. Then validate like:
if (isMember($Var,$AnotherVar) !== false){
//isMember has not returned false, so PHP is operating within these braces
}
Such a simple thing, which should be most effective.
If your wanting to assign true/false to $status['status']; then you are performing the right method, but wrong operator.
== is a comparision operator. Not assignment
= is an assignment operator, so your assignment should be:
$status['status'] = false;

Related

When a function returns true or false does it actually returns a string of true or false?

I have a basic simple question. Consider the following code
function checkNumber($number)
{
if (is_numeric($number))
{
return true;
}
else
{
return false;
}
}
$isValidNumber = checkNumber(123);
Will isValidNumber variable contain a string of value true?
It will return a bool value. Can you check it by var_dump($isValidNumber).
Result is:
bool(true)
It will always be a boolean because even if you just return is_numeric($number) it will be a bool because the function itself returns a boolean like explained here.
Even if you made useless stuff like
function checkNumber($number)
{
return $is_numeric($number);
}
$isValidNumber = checkNumber(123);
$number will be always an boolean in your case.

When would empty() return false and $var == '' return true?

Got an interesting issue. In some legacy code we have following statements.
if (empty($result['email_address']) && empty($result['mobile_number'])) {
$token = '';
} else {
$tokenFinder = new TokenFinder();
$tokenFinder->setEmailAddress($result['email_address']);
$tokenFinder->setMobileNumber($result['mobile_number']);
$token = $tokenFinder->generate();
}
The relevant bits of the token finder look like the following:
class TokenFinder{
public function setEmailAddress($email) {
$this->email = $email;
}
public function setMobileNumber($mobile) {
$this->mobile = $mobile;
}
public function generate(){
if ($this->email == '' && $this->mobile == ''){
Throw new Exception('TokenFinder: You cannot fetch a token with no email or mobile number');
}
Yesterday, for the first time ever, the exception in the generate() method was triggered. I have run all of the recipients in the failed message through this block of code and the exception doesn't trigger. The data has not changed since the Exception was thrown. It is a strange one.
Does anyone know any values which will lead empty($var) to evaluate to false and $var == '' to evalute to true.
empty() returns true in case of:
empty string
0 integer
0.0 float
0 as string
null
false
empty array
empty variable
(see http://php.net/empty)
The error must lie in php's tricky type juggling. It could be, that $result['email_address'] or $result['mobile_numer'] contain an object which __toString implementation return an empty string. emtpy will see an object and == '' sees an empty string.
There could be dozens of other cases though. So your best possibility is to get rid of the logic duplication (the if statements) and implement maybe a static method in TokenFinder like isDataValid and use it to check the array outside of the class.
PHP manual:
empty() Returns FALSE if var exists and has a non-empty, non-zero
value. Otherwise returns TRUE.

Return true if and only if all values in array are true?

So I have an array that contains all of the function calls to check the input of a form. I then have a foreach loop through the array to see if the returns from the validate functions are true or false. Depending on that outcome the function that the foreach is in returns either true or false. The problem I'm trying to figure out is how to return true just once if all of the validate functions come back true.
Here is my code:
public function valInputs()
{
$valArray = array(
valName($firstName),
valName($lastName),
valPhone($phone),
valEmail($email)
); // these functions return true/false depending on validation
foreach($valArray as $value)
{
if(!$value)
{
return false;
break;
}
else
{
return true; // the problem is, true gets returned X number of times
}
}
}
Any ideas on how to keep true from returning multiple times? Thank you for any help.
The return call stops the foreach loop AND the function. You can in fact just return true beneath the loop:
foreach($valArray as $value)
{
if(!$value)
{
return false;
// break is not needed, and should NOT be used in this case,
// as it stops the foreach loop.
// It will never be reached anyways, seeing how you return false just above.
}
}
return true;
If it reaches the end of the loop, it means it hasn't returned false. Hence it should return true.
An interesting way to do it would be
public function valInputs()
{
$valArray = array(
valName($firstName),
valName($lastName),
valPhone($phone),
valEmail($email)
); // these functions return true/false depending on validation
return array_product( $valArray ) === 1;
}
Why not just:
public function valInputs() {
return (valName($firstName) && valName($lastName) && valPhone($phone) && valEmail($email));
}
This will return true if all of them are true, false if at least one of them is false. Frankly I'm not sure why would you need a foreach loop there.
By definition, return ends the function. You can't return more than once.
Look at pst's comment, check to see if you are calling that function multiple times.

How can I quickly check if GET and POST variables in CodeIgniter are both set and numeric?

How can I quickly validate if a GET or POST variable in CodeIgniter is both set and numeric for use as error or status messages in views?
It is very tedious to do something like this each time each time I want to check variables:
if ($this->input->get('error', True)) {
if (is_numeric($this->input->get('error', True))) {
$data['error'] = $this->input->get('error', True);
}
}
get_numeric_input() for CodeIgniter
mixed get_numeric_input ( string $name [, bool $required = True [, string $source = "GET" [, bool *$xss_clean* = True ]]] )
Below is a function that I created because I was tired of checking if GET and POST variables existed and were numeric.
This was mainly used when handling errors or status messages, because I could use redirect("original_page.php?error=1"); to pass an error to the original page. On the original page, I could simply do if (isset($error)) { … } and display a message depending on the value. However, it was necessary to check these variables before sending them to the view in the interest of security. This process proved to be quite repetitive and tedious.
This function below is to be added to the bottom of wwwroot/application/system/core/Input.php
It is to be used as follows:
Example 1:
function index() {
if ($error = $this->input->get_numeric_input('error', True, "GET", True)) {
$data['error'] = $error;
}
}
In this example, if $_GET['error'] is both set and numeric, it will set $data['error'] to that value. If it is either not set and/or not numeric, it will terminate the script.
Example 2:
function index() {
if ($error = $this->input->get_numeric_input('error', False, "POST", True)) {
$data['error'] = $error;
}
}
In this example, if $_POST['error'] is both set and numeric, it will set $data['error'] to that value. If it is either not set and/or not numeric, it will continue and not set any values in the $data array.
The first argument is the variable name to be checked. The second variable is the boolean that makes the check required or not. If you have this set to TRUE, then if the variable is not set OR if it is not numeric, it will show an error and immediately terminate the script. If set to False, then it will will simply return False, and the script will move on. The third variable is either POST or GET, and will determine if the function looks for the variable in the $_GET or $_POST arrays. Finally, the fourth variable indicated whether or not the values will be XSS_CLEAN when returned.
NOTE: Both the second, third, and fourth arguments are optional, and default to True, “GET,” and True, respectively.
Here is the code:
function get_numeric_input($name, $required = True, $source = "GET", $xss_clean = True) {
if ($source === "GET") {
if ($this->get($name, $xss_clean)) {
if (is_numeric($this->get($name, $xss_clean))) {
return $this->get($name, $xss_clean);
} else {
if ($required) {
show_error("$source variable $name is not numeric!");
log_message('error', "$source variable $name is not numeric!");
return False;
} else {
return False;
}
}
} else {
if ($required) {
show_error("$source variable $name is not set!");
log_message('error', "$source variable $name is not set!");
return False;
} else {
return False;
}
}
} elseif ($source === "POST") {
if ($this->post($name, $xss_clean)) {
if (is_numeric($this->post($name, $xss_clean))) {
return $this->post($name, $xss_clean);
} else {
if ($required) {
show_error("$source variable $name is not numeric!");
log_message('error', "$source variable $name is not numeric!");
return False;
} else {
return False;
}
}
} else {
if ($required) {
show_error("$source variable $name is not set!");
log_message('error', "$source variable $name is not set!");
return False;
} else {
return False;
}
}
}
}
A possible alternative is to extend the form validation so that you would have a way to validate $_GET aswell. Using the form validation library does save time imo (an extended version - fit to your needs - is advisable).
CodeIgniter Validation: possible to validate GET query strings? talks about this.
Just use an intermediary variable, for a short and fast code:
$input_error = $this->input->get('error');
$data['error'] = ctype_digit($input_error) ? $input_error : FALSE;
If you really want a one-liner:
function validate_integer_input($input) {
return ctype_digit($input) ? $input : FALSE;
}
$data['error'] = validate_integer_input($this->input->get('error'));
$data['error'] will always be set, which is a good thing, because $data will always be set in your view, so you can simply do if ($data) instead of if (isset($data)).
When dealing with GET and POST input you have to know some aspects of typing. For the most important:
A GET/POST input, of course if it is set, is always of type string.
Only '' (empty) and '0' strings evaluate to FALSE, all other values evaluate to TRUE.
ctype_digit() expects a string, but this code may pass it FALSE (from CI->input). But it's fine, as FALSE casts to an empty string.
As a side note, XSS filtering is not needed for this case.
XSS filtering has quite a performance impact and should be activated only when needed. A rule of thumb is that the filtering is needed for data which is displayed or included wherever in the HTML source.
For this case, we already made sure the input can only contain digits, so we're safe.

String value equals true

I have a function that returns TRUE or FALSE or "Test_operation", and I am looping it to do some things. As you can see the value of $comment_reply is Test_operation.
$comment_reply = $this->Profunction->insert_comments();
echo $comment_reply; // returns Test_operation
if ($comment_reply==TRUE)
{
echo json_encode('Success');
}
elseif($comment_reply==FALSE)
{
echo json_encode('Failed');
}
elseif($comment_reply =="test_operation")
{
echo json_encode('This Action Cannot be done!');
}
But still
if ($comment_reply==TRUE)
{
echo json_encode('Success');
}
This portion getting executed. Why does it happen?
In that function I am returning like this:
return TRUE; // if all success
return FALSE; // if there is some problems
return "Test_operation"; //No insertion need to be done,may be for preview purpose.
SOLVED : I changed bool values to string.
So it will be
return 'TRUE'; // if all success
return 'FALSE'; // if there is some problems
return "Test_operation"; //No insertion need to be done,may be for preview purpose.
Not sure it's your issue, but if you want to enforce equality by type and value, use the === operator.
You can check this out in more detail on the comparison operator page.
Happy coding
Try using === instead of ==

Categories