I set a cookie on a visitor's PC to show a notice once every 24 hours. Recently I started getting the following error in my error log:
PHP: undefined index notice in **
I use the following code to check if the cookie exists with value and if not show notice:
if($_COOKIE['notice'] != 'yes')
echo 'notice';
}
I can use the following to avoid the PHP notice:
if((isset($_COOKIE['notice']) || !isset($_COOKIE['notice'])) && $_COOKIE['notice'] != 'yes')
Is there a way to do this check in one step only like I was doing or in a similar way?
Thanks
The index 'notice' in your source does not match the reported index 'test' in the error message. To avoid notices, you validate a variable or an index before reading it.
Here are two functions for the validation.
isset()
Is a positive check that the variable/index is set and not NULL
if (isset($_COOKIE['notice']) && $_COOKIE['notice'] === 'yes') {
// success
echo 'Cookie equals "yes".';
}
You can use && (and) for a second condition, that has to be TRUE, too.
empty()
Is a negative check that the index/variable does not exists or has a value that is considered empty (NULL, 0, '', array()).
if (empty($_COOKIE['notice']) || $_COOKIE['notice'] !== 'yes') {
// error
echo 'Cookie does not exists, is empty or does not equal "yes".';
}
You can use || (or) to combine that with additional conditions that need to be FALSE, too.
Or use the operator:
??
The operator assign a default value if the variable/index is not set or NULL:
$noticeCookie = (string)($_COOKIE['notice'] ?? 'no');
if ($noticeCookie === 'yes') {
// success
echo 'Cookie equals "yes".';
}
You always need to know if a variable is set before try to find what is inside, so yes.. you need to do the check. Also, your logic is wrong.. you are checking if notice is or isn't set (allways true) and checking if notice is "yes".
The code should be something like this:
if ( (!isset($_COOKIE['notice'])) || ( (isset($_COOKIE['notice'])) && ($_COOKIE['notice'] != 'yes') ) ) {
//Show the notice
}
Related
if ($user_id == NULL || $user_name == NULL || $user_logged == NULL) {
$user_id = '-1';
$user_name = NULL;
$user_logged = NULL;
}
if ($user_admin == NULL) {
$user_admin = NULL;
}
Is there any shortest way to do it ?
And if i right, it should be tested with is_null?
It's possible $user_id, $user_name and $user_logged write in one line (maybe array?) without repeating NULL ?
If you want to test whether a variable is really NULL, use the identity operator:
$user_id === NULL // FALSE == NULL is true, FALSE === NULL is false
is_null($user_id)
If you want to check whether a variable is not set:
!isset($user_id)
Or if the variable is not empty, an empty string, zero, ..:
empty($user_id)
If you want to test whether a variable is not an empty string, ! will also be sufficient:
!$user_id
You can check if it's not set (or empty) in a number of ways.
if (!$var){ }
Or:
if ($var === null){ } // This checks if the variable, by type, IS null.
Or:
if (empty($var)){ }
You can check if it's declared with:
if (!isset($var)){ }
Take note that PHP interprets 0 (integer) and "" (empty string) and false as "empty" - and dispite being different types, these specific values are by PHP considered the same. It doesn't matter if $var is never set/declared or if it's declared as $var = 0 or $var = "". So often you compare by using the === operator which compares with respect to data type. If $var is 0 (integer), $var == "" or $var == false will validate, but $var === "" or $var === false will not.
here i have explained how the empty function and isset works please use the one that is appropriate also you can use is_null function also
<?php
$val = 0;
//evaluates to true because $var is empty
if (empty($val)) {
echo '$val is either 0, empty, or not set at all';
}
//evaluates to true because $VAR IS SET
if (isset($val)) {
echo '$val is set even though it is empty';
}
?>
empty() is a little shorter, as an alternative to checking !$user_id as suggested elsewhere:
if (empty($user_id) || empty($user_name) || empty($user_logged)) {
}
To check for null values you can use is_null() as is demonstrated below.
if (is_null($value)) {
$value = "MY TEXT"; //define to suit
}
Please define what you mean by "empty".
The test I normally use is isset().
you can use isset() routine .
also additionaly you can refer an range of is_type () functions like
is_string(), is_float(),is_int() etc to further specificaly test
1.
if(!($user_id || $user_name || $user_logged)){
//do your stuff
}
2 . No. I actually did not understand why you write such a construct.
3 . Put all values into array, for example $ar["user_id"], etc.
<?php
$nothing = NULL;
$something = '';
$array = array(1,2,3);
// Create a function that checks if a variable is set or empty, and display "$variable_name is SET|EMPTY"
function check($var) {
if (isset($var)) {
echo 'Variable is SET'. PHP_EOL;
} elseif (empty($var)) {
echo 'Variable is empty' . PHP_EOL;
}
}
check($nothing);
check($something);
check($array);
Its worth noting - and I only found this out after nearly 9 years of PHP coding that the best way of checking any variable exists is using the empty() function. This is because it doesn't generate errors and even though you turn them off - PHP still generates them! empty() however won't return errors if the variable doesn't exist. So I believe the correct answer is not to check if its null but to do the following
if (!empty($var) && is_null($var))
Note the PHP manual
variable is considered empty if it does not exist or if its value equals FALSE
As opposed to being null which is handy here!
Felt compelled to answer this because of the other responses. Use empty() if you can because it covers more bases. Future you will thank me.
For example you will have to do things like isset() && strlen() where instead you could use empty(). Think of it like this empty is like !isset($var) || $var==false
The best and easiest way to check if a variable is empty in PHP is just to use the empty() function.
if empty($variable)
then
....
I need to check if this $_SESSION['1'] || $_SESSION['2'] isset or not
I tried this
ob_start();
session_start();
if (!isset($_SESSION['log']) && $_SESSION['log'] !== 1) {
if (!isset($_SESSION['insAdmin']) && $_SESSION['insAdmin'] !== 1) {
header("Location:sessionManager/login.php");
}
}
but if $_SESSION['insAdmin'] isset
I get a notes
( ! ) Notice: Undefined index: log in
C:\wamp\www\mysite\en\admin\headers.php on line 13
You're contradicting yourself:
!isset($_SESSION['log']) & $_SESSION['log'] !== 1
You're basically saying if $_SESSION['log'] is not set and $_SESSION['log'] is not 1 which doesn't make sense.
If $_SESSION['log'] is not set then trying to access it's value through $_SESSION['log'] (with the 2nd expression after &&) will result in an undefined index of course.
You should remove the !:
if (isset($_SESSION['log']) && $_SESSION['log'] !== 1) {
if (isset($_SESSION['insAdmin']) && $_SESSION['insAdmin'] !== 1) {
header("Location:sessionManager/login.php");
}
}
You normally use isset to test if a variable contains a value before checking it's actual value.
But you check if the variable is NOT set !isset($_SESSION['log'] and then check it's value which of course will always cause the notice if log is not set.
You're checking if it's not set, check if it's set instead.
if (isset($_SESSION['insAdmin']) && $_SESSION['insAdmin'] !== 1) {
header("Location:sessionManager/login.php");
}
I have this condition, what I am trying to do is say, if $_GET['subpage'] is not equal to registerupcoming then do this, but I get an error:
Notice: Undefined index: subpage in /Applications/XAMPP/xamppfiles/htdocs/losanihomes/views/includes/header.php on line 26
So I tried the following:
if(isset($_GET['subpage']) && $_GET['subpage'] != 'registerupcoming'){
//Do Something
}
but the problem is, if subpage is not set, then it does not go into the condition, I only want to not go into this condition if subpage is not equal to registerupcoming
Just change your && to || and isset() to !isset():
if(!isset($_GET['subpage']) || $_GET['subpage'] != 'registerupcoming'){
//Do Something
}
Now if that variable isn't set or has the wrong value you will redirect.
In this snippet of code we type $inputs['user_id'] 3 times.
if (isset($inputs['user_id']) && $inputs['user_id']) { // The consumer is passing a user_id
doSomethingWith($inputs['user_id']);
}
What's the most readable and robust refactoring I can do to avoid the duplication and avoid any notice that the index user_id doesn't exist?
Thanks.
Here nothing is wrong with the duplication. You cannot assign $inputs['user_id'] to a variable before checking if it is set, otherwise this will produce a Notice undefined index ....
The only thing here could be done is to omit the isset call and use !empty instead, like this:
if(!empty($inputs['user_id'])) {
doSomething($inputs['user_id']);
}
Now You are only typing it twice and the check
!empty($inputs['user_id'])
equals to
isset($inputs['user_id']) && $inputs['user_id']
EDIT: based on a comments, here is a quote from documentation:
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
So either empty(0) or empty('0') will return true, that means
if(!empty('0') || !empty(0)) { echo "SCREW YOU!"; }
will echo nothing... Or, in polite way, I will repeat the statement above:
!empty($inputs['user_id']) === (isset($inputs['user_id']) && $inputs['user_id'])
EDIT 2:
By omitting the isset and replacing by !empty the variable is still checked, whether the index is already set, please read the documentation, which says:
No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.
What about this:
// put validation check to the function body
function doSomethingWith($userId) {
if($userId === -1) {
// if this is not a valid user id -> return
return;
}
// do something ...
}
// initalize $user with proper default values.
// doing so you can be sure that the index exists
$user = array(
'id' => -1,
'name' => '',
...
);
// merge inputs with default values:
$user = array_merge($user, $request);
// now you can just pass the value:
doSomethingWith($user['id']);
Below might not be the best way for every situation, but definitely cuts down on the repetition.
Your example code would turn into:
doSomethingWith($inputs['user_id']);
and your function would look like this (notice the argument supplied by reference, to avoid the undefined variable warning):
function doSomethingWith(&$userID) {
if (empty($userID)) return;
// ... actual code here ...
}
Assuming that 0 and "" and null are not valid user_ids:
if ($id = $inputs['user_id']) {
doer($id);
}
YOu can also do with evil # to avoid notice in your logs, (I don't like this way):
if ($id = #$inputs['user_id']) {
doer($id);
}
In PHP, how would one check to see if a specified item (by name, I think - number would probably also work) in an array is empty?
Types of empty (from PHP Manual). The following are considered empty for any variable:
"" (an empty string)
0 (0 as an integer)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
So take the example below:
$arr = array(
'ele1' => 'test',
'ele2' => false
);
1) $arr['ele3'] is not set. So:
isset($arr['ele3']) === false && empty($arr['ele3']) === true
it is not set and empty. empty() checks for whether the variable is set and empty or not.
2) $arr['ele2'] is set, but empty. So:
isset($arr['ele2']) === true && empty($arr['ele2']) === true
1) $arr['ele1'] is set and not empty:
isset($arr['ele1']) === true && empty($arr['ele1']) === false
if you wish to check whether is it empty, simply use the empty() function.
if(empty($array['item']))
or
if(!isset($array['item']))
or
if(!array_key_exists('item', $array))
depending on what precisely you mean by "empty". See the docs for empty(), isset() and array_key_exists() as to what exactly they mean.
<?php
$myarray=array(1,5,6,5);
$anotherarray=array();
function checkEmpty($array){
return (count($array)>0)?1:0;
}
echo checkEmpty($myarray);
echo checkEmpty($anotherarray);
?>
(for checking if empty result 1 else 0);
Compactness is what I persue in my code.
i had such situation where i was getting tab it last index of array so if put things together then this might work for the most of cases
<?php
if( ctype_space($array['index']) && empty($array['index']) && !isset($array['index']) ){
echo 'array index is empty';
}else{
echo 'Not empty';
}