php testing isset() and empty() in a function - php

I am trying to encapsulate isset() and empty() in a function.
It worked fine on my home development sever (apache 2.4.3, PHP 5.2.17 under WinXP). When I ported it to my university Linux machine running Fedora, I got a notice about undefined index.
I checked my php.ini on my home computer, and error reporting is set to all. I put error_reporting(E_ALL); in my PHP script to try duplicate the error. It didn't happen.
Question 1: Why am I not getting the notice on my home development computer?
Here is my function:
<?php
function there($s) {
if (! isset($s)) {
return false;
}
if (empty($s)) {
return false;
}
return true;
}
?>
Here I test if a session variable exists:
if (! there($_SESSION['u'])) {
$_SESSION['u'] = new User();
}
I switched my function so that I test empty() before I test isset() thinking this will avoid getting the notice. I haven't had a chance yet to test this at school.
Question 2: Does empty() in general avoid giving a notice if the variable is undefined, or not set?
Question 3: Can I use my there() function to do this, or will I get the notice just by passing the undefined or unset parameter?

isset and empty are not functions, they are language constructs. As such, they can get away with such things as reading the literal variable name instead of trying to access the value. Any function you define can't do that.
With that in mind, there is no need to test for both. empty is a superset of isset, so you only really need to check for empty.

Your function is almost equivalent to !empty:
if (empty($_SESSION['u'])) {
$_SESSION['u'] = new User();
}
The only difference is: your wrapper function will complain if it's passed a variable that doesn't exist - whereas, as a language construct empty will not (and neither will isset).
Your sub-questions
Why am I not getting the notice on my home development computer?
Probably because you've got error reporting turned off.
Does empty() in general avoid giving a notice if the variable is undefined, or not set?
Yes.
Can I use my there() function to do this, or will I get the notice just by passing the undefined or unset parameter?
You will get notices about undefined variables.

As a way of proving #Kolink 's fine reply really, something which I had not realised ...
echo '<form action="" method=POST>
<input type=text value="" name="string" />
<input type=text value=0 name="int" />
<input type=submit />
</form>';
if( empty($_POST['string'] ) ){
var_dump( $_POST['string']) ;
}
if( empty($_POST['int'] ) ){
var_dump( $_POST['int']) ;
}
if( empty($_POST['something'] ) ){
echo 'something was not set, but you cannot var_dump it without a warning';
}

I realize this is an old thread, and it already has an accepted answer. So, I will not answer the questions again here. But for completeness sake and in the hope that it may help others I am sharing something I use.
Take a look at the following code:
<?php
echo var_dump($_SESSION['something']);
This will give you:
PHP Notice: Undefined variable: _SESSION in - on line 2
NULL
But if you do this:
<?php
echo var_dump(mycheck($_SESSION['something']));
function mycheck( &$var ){ // Note the & so we are passing by reference
return $var;
}
You will get:
NULL
This is because internally the $var variable will get created the instant the function is called. But since the $_SESSION['something'] does not exist, the $var is getting set to null which is then returned. Voila, notice gone. But be aware that the variable $_SESSION['something'] has now been created internally, even though isset($_SESSION['something']) will still return false because isset determines 'if a variable is set and is not NULL'.
PHP manual for isset: http://php.net/manual/en/function.isset.php

Related

PHP: $_REQUEST is not showing value of get parameter

I'm running into a strange problem where $_REQUEST is not showing the value of a parameter I am explicitly passing e.g.
http://example.com/strange.php?parName=1234
strange.php:
<?php
$foo = $_REQUEST['parName'] ;
echo $foo ;
?>
I have looked in the Inspector and the Network tab actually shows the correct query string parameter.
I have carried out some tests.
in test.html:
link
in request.php:
$foo = $_REQUEST['parName'];
echo $foo ;
I have also tried:
$foo = $_GET['parName'];
echo $foo ;
Both of which work.
Therefore thinking about the strange issue you are encountering, you will need carry out various checks:
Is the query string getting passed? See $_SERVER["QUERY_STRING"]
Check the request method $_SERVER["REQUEST_METHOD"]
Check to see if the parName variable isset
if(isset($_GET['parName'] )) {
$foo = $_GET['parName'];
echo $foo ;
}
else { "echo query string not received";
}
Check your error log to see what Apache is saying?
What data is actually contained in the parName variable?
var_dump($_REQUEST['parName'])
Once you've run all these tests, and the issue is still not resolved, please post your results so we can consider other possible paths to solving this problem.

warning if variable does not exist

If I try to use a variable which doesnt even exist in PHP, I dont get any errors or notices. In the example below the return value is "null". I'd like to see some form of notification if that happens so that I can find bugs in my code more easily.
echo $doesNotExist -> something; //returns null
The error reporting in my php.ini is the following
error_reporting = E_ALL
What do I have to do to see notifications when accessing varibles that don't exist?
To clarifiy this:
I know that I can check if a variable exists by using isset(). That's not what I want though. I want to get a notification in case I accidentaly try to use a variable that does not exists. For example if I misspell the name of a variable.
display_errors = On is in my php.ini
As well as error_reporting, you may need to turn on display_errors, which should be off in production environments.
Production environments can use log_errors instead, which outputs the errors to the file named in the error_log directive.
I generally use thw following;
if(isset($var) && !empty($var)) {
//Do something with $var
} else {
//Define $var
}
As said in a previous answer you also need to turn error reporting on in the php.ini
what you do is perfectly valid in PHP. It just creates and instantiates that variable at runtime, and doesn't throw an error like other languages.
even isset would not work too well. Say you set an object variable with a wrong name. If you do isset on that name, it will be true. If you do isset on the correct name, it will be false.
Example:
class test{
public $name1;
}
$test = new test;
$test->name2 = 'wrong';
var_dump($test);
prints: object(test)#1 (2) { ["name1"]=> NULL ["name2"]=> string(5) "wrong" }

Constant, isset and empty evaluation

Does anyone know how isset and empty is interpreted by the translator, or how the translator treats undefined variables?
To expand on my question, I have the below code in my include file:
define('USER_AUTH', !empty($_SESSION['username']) && !empty($_SESSION['status'])); //user is verified
define('ACC_IS_PENDING', $_SESSION['status'] == '0');//checks to see if user status is pending which has a status of 0
USER_AUTH is used as a quick hand to check if user is authenticated. ACC_IS_PENDING is used as a quick hand for when the account status is pending. However, PHP gives me a notice to advise me that $_SESSION['status'] in my second line of code is undefined. I know that it is undefined, but I haven't used it yet! How dare you tell me what I already know. LoL
However, when I trick the code with the below:
define('USER_AUTH', !isempty($_SESSION['username']) && !isempty($_SESSION['status']));
define('ACC_IS_PENDING', $_SESSION['status'] == '0');
Where isempty() is a custom made function that will always return FALSE. Then no notice!
Alternatively, if I use the below code:
define('USER_AUTH', notempty($_SESSION['username']) && notempty($_SESSION['status']));
define('ACC_IS_PENDING', $_SESSION['status'] == '0');
Where notempty() always return TRUE, then again no notice.
Am I right in saying that the translator checks that the variable has been tested once, and that if the test resulted in true, then the translator sees this as the variable has been defined?
If this was the case, then what about isset and empty? They both seem to give me notices no matter if the evaluation is true or false.
define('USER_AUTH', isset($_SESSION['username']) && isset($_SESSION['status']));
define('ACC_IS_PENDING', $_SESSION['status'] == '0');
and
define('USER_AUTH', empty($_SESSION['username']) && empty($_SESSION['status']));
define('ACC_IS_PENDING', $_SESSION['status'] == '0');
Apologies for the long winded question. This seems trivial, but it would be nice to have a quick defined constant without having to get notices! Any help in explanation or a better solution for such trivial task would be appreciated, thanks!
PHP complains because the index 'status' is not defined in the array. You would need to write
!isset($_SESSION['status']) || empty($_SESSION['status']
When you "trick" the code as described, PHP will never try to access the non-existing array index, which is why you don't get any notice.
In the fourth code example (with isset), you are still accessing the non-existing array index in the second line of code, so I suspect that's why there's still a notice.
a) If you wants to use $_SESSION['status'], you have to check first that the variable is not empty ( see http://www.php.net/manual/fr/function.isset.php for more details) :
if (isset($_SESSION['status'])) {
// here the value exists and can be used
Do something...
} else {
// here the value does not exist and cannot be used
}
b) I believe that
empty($_SESSION['username']) && !empty($_SESSION['status'])
is not constant : it varies from one run to the other. You may want to use
$user_is_logged = empty($_SESSION['username']) && !empty($_SESSION['status']);
and use the variable $user_is_logged instead of a constant. See this section http://www.php.net/manual/fr/language.constants.php for a speek about constants.

register_globals off - now I get an odd undefined but it shouldn't be

What I had BEFORE was...
if(DEBUGMODE) $debug_err_msgs[] = 'Some error'; // add a new error to the array
... more code here...
if(DEBUGMODE)$debug_err_msgs[] = 'Some error'; // add a new error to the array
which worked great EXCEPT in functions. SO... I decided to make it GLOBAL by using the $_GLOBALS array. I originally liked the 1st method I chose because it kept adding to the array and I could dump it later on to view what was happening.. Using the $_GLOBALS['debug_err_msgs'] and $_GLOBALS['errorh_string'] is forcing me to .= (append) the string to the previous one (which is ok... I didn't think you could go... $_GLOBALS['something'][] and keep adding to the array like I did before I changed my code. SO.. I made changes as below...
PHP
<?php
error_reporting(E_ALL);
set_error_handler("ErrorHandler");
$_GLOBALS['errorh_string'] = "";
if(DEBUGMODE) $_GLOBALS['debug_err_msgs'] = "";
if(DEBUGMODE) $_GLOBALS['debug_err_msgs'] .= 'La la la, some errors';
if(DEBUGMODE) $_GLOBALS['debug_err_msgs'] .= 'more errors... etc';
function ErrorHandler($errno, $errstr, $errfile, $errline)
{
// if ($errno == 8) return;// 8 is undefined variables
$error = "<b>Error[</b>$errno<b>] </b>$errstr<br />";
$_GLOBALS['errorh_string'] .= $error; // append new error to the global string
return true; // dont execute the php internal error handler
}
?>
ERRORS IM GETTING
Notice: Undefined index: errorh_string in /debugOpenBlock.php on line 14
Notice: Undefined index: errorh_string in /debugOpenBlock.php on line 14
Which in the code above, is INSIDE the function
$_GLOBALS['errorh_string'] .= $error; // GIVES ME UNDEFINED
Here is what's weird... if I change the line to read...
$_GLOBALS['errorh_string'] = $error; // NO ERROR NOW
I even tried
$_GLOBALS['errorh_string'] = $_GLOBALS['errorh_string'] . $error; // GIVES ME UNDEFINED
If 'errorh_string' is a literal? why do I get undefined in it.!?!??! Am I missing something about GLOBALS?
As I was writting this I was thinking I could have used
global $debug_err_msg[]; // make this array global
instead of changing all my code to the way I have it now but... I'm curious what this problem is now... I hate not knowing something :)
BTW - I just recently turned off register_globals in the PHP.INI file. Could this have anything to do with it (note: I NEVER used $_SESSION['somevariable'] as $somevariable (mainly because I didn't know you could do that but... doesn't matter anyways)).
I've read piles of articles about superglobals, register_globals etc but nothing sheds any light on this..
Awaiting wisdom oh greater than I web developers :)
I can't find another problem, so the issue seems that you just used the wrong variable name. It is called $GLOBALS, not $_GLOBALS - unlike the input arrays. (It's not affected by the register_globals setting btw.)
global $debug_err_msg;
You should actually prefer this method. That makes using the variable more legible than with the $GLOBALS[] access, and it also shows that you intentionally share that variable.

Undefined index: When converting cookie value to variable

The problem
The following code produces this error from the line "print $readerStatus" -
Undefined index: readerStatus
Code
<?php
//Get Cookie Value
if (isset($_COOKIE['readerStatus'])) {
$readerStatus=$_COOKIE['readerStatus'];
} Else {
$readerStatus="Not Set";}
echo "The value of Cookie readerStatus is " . $_COOKIE['readerStatus'];
print $readerStatus;
?>
Background
The goal is simply that if a cookie is set I want to pass the value into a Javascript. My strategy is as follows:
Get the value from the cookie
Set a variable to the value of the cookie
Then use a php echo inside of the Javascript to transfer the value.
It works as expected but Eclipse is giving me the error and so I assume there is something wrong with the above code.
I'd appreciate any pointers on possible sources of the problem.
Thanks
Is this working?
<?php
//Get Cookie Value
if (isset($_COOKIE['readerStatus'])) {
$readerStatus=$_COOKIE['readerStatus'];
} else {
$readerStatus="Not Set";
}
echo ("The value of Cookie readerStatus is ".$readerStatus);
print ($readerStatus);
?>
This is a warning, not an error. However, you can skip the error by using array_key_exists. Generally, I'm not a fan of isset for this kind of checking.
if (array_key_exists('readerStatus', $_COOKIE))
{
$readerStatus=$_COOKIE['readerStatus'];
}
else
{
$readerStatus='Not Set';
}
echo 'The value of Cookie readerStatus is '. $readerStatus;
Some IDEs are less forgiving than the PHP parser itself. That being said, do you get any errors or notices when running the code? Variables in PHP are implicitly declared, so the undefined index message is simply a NOTICE (that can be ignored) regarding the accessing of an array element without it existing first.
If you check it exists prior to accessing it like this, you shouldn't have a problem.
$readerStatus = isset($_COOIKE['readerStatus']) ? $_COOIKE['readerStatus'] : '';

Categories