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'] : '';
Related
Something makes me crazy, I get an Undefined variable if I declare a variable in an IF statement. If I declare this variable above the IF statement, the PHP Notice disapear.
My code :
if($tab_sel==FILENAME_DEFAULT){ // FILENAME_DEFAULT = index.php
if(...){
some functions
}
$nb_pages=ceil($count/$limit) : 0;
}
echo $nb_pages; //4000 is displayed on the page (OK),
but in the Nginx log, I get :
FastCGI sent in stderr: "PHP message: PHP Notice : Undefined variable nb_pages in /.../index.php
but when I load the page, I can see that nb_page is displayed correctly (example: value is 4000), but in the log, undefined variable..
In my example, if I declare nb_pages above "if($tab_sel==FILENAME_DEFAULT){", the undefined disapear.
Any idea?
That's because you're creating the variable inside a if that can fail to pass. In this case, the variable would be undefined and PHP will throw an error since it couldn't find the variable that you are asking for afterwards.
Declare it before the if and you will be just fine.
$nb_pages;
if($tab_sel==FILENAME_DEFAULT){
if(...){
I think it might me an environment issue. Try to put both FILENAME_DEFAULT and $nb_pages into a log file:
file_put_contents(
'test.log',
date('[Y-m-d H:i:s] ')
. FILENAME_DEFAULT . "\t" . #$nb_pages . PHP_EOL,
FILE_APPEND
);
The # will prevent the warning message.
I found why it didn't work :
in case of a 404 error page (called FILENAME_404)
I also use the index.php file in which I call the variables undeclared.
that's why the Nginx error said about index.php, not because it doesn't go into if($tab_sel==FILENAME_DEFAULT){ but because in some other cases I use also index.php with tab_sel=FILENAME_404
thank you everyone!
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.
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
I don't understand why someone is using the # in the code, I have seen it with mysql connections but I don't know what it means.. thanks!
$player_name_orig = #$_GET['player'];
if (!$player_name_orig) {
die('You must specify a player name');
}
The # is the error suppression operator.
In this specific context, it's a (wrong!) way to avoid PHP giving a notice if the player key does not exist in $_GET:
If you try this:
unset($_GET['player']); // to make sure
echo $_GET['player'];
You get:
Notice: Undefined index: player in F:\dev\www\index.php on line 35
While if you try this:
unset($_GET['player']); // to make sure
echo #$_GET['player'];
There is no output.
The correct way to do this:
if (empty($_GET['player']) {
die('You must specify a player name');
}
The # will stop any errors from appearing and return false on an error.
So in your code if $_GET['player'] does not exist then the code will go into the if statement
# Means to ignore errors such as the variable not being set.
the "#" is used to prevent any warning or error message to appear. It's a really bad habit. Doing that a lot of hidden operations are done (removing error handler, and putting it back after).
The right way to do that operation is:
// my_security_filter() is a function that can render FALSE and remove any dangerous thing
$player_name_orig = array_key_exists('player',$_GET)? my_security_filter($_GET['player']) : FALSE;
if (FALSE===$player_name_orig) { ...
I thought I knew how to use arrays until I started storing form filling errors in them. So here is the situation: I want to declare an array at the beginning of my PHP document. Then throughout the document there is validation and at each validation the array is filled with an error if an error should be produced. Then at the end of the document I want to echo these errors into a specific on the page. So here is what I have now:
$errors = array();//declares array
if(/*some qualifier*/) {//username validation
} else {
$errors[] = "<p>Please enter a valid username</p>";
}
if(/*some qualifier*/) {//email validation
} else {
$errors[] = "<p>Please enter a valid email</p>";
}
echo '<div id="errors">';//errors div
foreach ($errors as $value) {//fills error div with the errors LINE 60
echo "$value<br />\n";
}
echo '</div>';
So... what is wrong with that? I keep getting an error that errors is an undefined variable when it tries to echo the errors.
The error as given in the comments:
An error occurred in script 'file path' on line 160: Undefined variable: errors
Update: seems like its a problem with something weird in my code. If you feel like looking through 217 lines of code here is all the code: http://pastebin.com/YkERYpeF
I have seen your code. You did only declare $errors inside a condition:
//if the user has registered
if (isset($_POST['submitted'])) {
require_once (MYSQL); //gets the database connection
$errors = array(); // declares the errors array that will be printed at end of validation if needed
PHP arrays work great. You are declaring variables in a conditional scope and using them in a global scope. And PHP can't imagine you want to use that variable in the global scope.
You ought to indent your code as well, but you can perfectly define $errors just below $bodyId and PHP won't complain anymore.
Chances are something in one of your validation blocks is using $errors for its own purposes, some function called somewhere in there uses global $errors, or something is screwing it up in some other manner.
I've found the quickest way to track down this sort of thing is to insert a check on the variable somewhere in the middle and basically do a binary search on the code until you track down just where the variable is being reset.