I\'m running a PHP script and continue to receive errors like:
Notice: Undefined variable: my_variable_name in C:\\wamp\\www\\mypath\\index.php on line 10
When dealing with files, a proper enctype and a POST method are required, which will trigger an undefined index notice if either are not included in the form.
The manual states the following basic syntax:
HTML
<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
PHP
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
Reference:
From the vast wisdom of the PHP Manual:
Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized. Additionally and more ideal is the solution of empty() since it does not generate a warning or error message if the variable is not initialized.
From PHP documentation:
No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.
This means that you could use only empty()
to determine if the variable is set, and in addition it checks the variable against the following, 0
, 0.0
, ""
, "0"
, null
, false
or []
.
Example:
$o = [];
@$var = ["",0,null,1,2,3,$foo,$o['myIndex']];
array_walk($var, function($v) {
echo (!isset($v) || $v == false) ? 'true ' : 'false';
echo ' ' . (empty($v) ? 'true' : 'false');
echo "\n";
});
Test the above snippet in the 3v4l.org online PHP editor
Although PHP does not require a variable declaration, it does recommend it in order to avoid some security vulnerabilities or bugs where one would forget to give a value to a variable that will be used later in the script. What PHP does in the case of undeclared variables is issue a very low level error, E_NOTICE
, one that is not even reported by default, but the Manual advises to allow during development.
Ways to deal with the issue:
Recommended: Declare your variables, for example when you try to append a string to an undefined variable. Or use isset() / !empty() to check if they are declared before referencing them, as in:
//Initializing variable
$value = ""; //Initialization value; Examples
//"" When you want to append stuff later
//0 When you want to add numbers later
//isset()
$value = isset($_POST['value']) ? $_POST['value'] : '';
//empty()
$value = !empty($_POST['value']) ? $_POST['value'] : '';
This has become much cleaner as of PHP 7.0, now you can use the null coalesce operator:
// Null coalesce operator - No need to explicitly initialize the variable.
$value = $_POST['value'] ?? '';
Set a custom error handler for E_NOTICE and redirect the messages away from the standard output (maybe to a log file):
set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)
Disable E_NOTICE from reporting. A quick way to exclude just E_NOTICE
is:
error_reporting( error_reporting() & ~E_NOTICE )
Suppress the error with the @ operator.
Note: It's strongly recommended to implement just point 1.
This notice appears when you (or PHP) try to access an undefined index of an array.
Ways to deal with the issue:
Check if the index exists before you access it. For this you can use isset() or array_key_exists():
//isset()
$value = isset($array['my_index']) ? $array['my_index'] : '';
//array_key_exists()
$value = array_key_exists('my_index', $array) ? $array['my_index'] : '';
The language construct list() may generate this when it attempts to access an array index that does not exist:
list($a, $b) = array(0 => 'a');
//or
list($one, $two) = explode(',', 'test string');
Two variables are used to access two array elements, however there is only one array element, index 0
, so this will generate:
Notice: Undefined offset: 1
$_POST
/ $_GET
/ $_SESSION
variableThe notices above appear often when working with $_POST
, $_GET
or $_SESSION
. For $_POST
and $_GET
you just have to check if the index exists or not before you use them. For $_SESSION
you have to make sure you have the session started with session_start() and that the index also exists.
Also note that all 3 variables are superglobals and are uppercase.
Related:
undefined index means in an array you requested for unavailable array index for example
<?php
$newArray[] = {1,2,3,4,5};
print_r($newArray[5]);
?>
undefined variable means you have used completely not existing variable or which is not defined or initialized by that name for example
<?php print_r($myvar); ?>
undefined offset means in array you have asked for non existing key. And the solution for this is to check before use
php> echo array_key_exists(1, $myarray);
Regarding this part of the question:
Why do they appear all of a sudden? I used to use this script for years and I've never had any problem.
No definite answers but here are a some possible explanations of why settings can 'suddenly' change:
You have upgraded PHP to a newer version which can have other defaults for error_reporting, display_errors or other relevant settings.
You have removed or introduced some code (possibly in a dependency) that sets relevant settings at runtime using ini_set()
or error_reporting()
(search for these in the code)
You changed the webserver configuration (assuming apache here): .htaccess
files and vhost configurations can also manipulate php settings.
Usually notices don't get displayed / reported (see PHP manual) so it is possible that when setting up the server, the php.ini file could not be loaded for some reason (file permissions??) and you were on the default settings. Later on, the 'bug' has been solved (by accident) and now it CAN load the correct php.ini file with the error_reporting set to show notices.
I used to curse this error, but it can be helpful to remind you to escape user input.
For instance, if you thought this was clever, shorthand code:
// Echo whatever the hell this is
<?=$_POST['something']?>
...Think again! A better solution is:
// If this is set, echo a filtered version
<?=isset($_POST['something']) ? html($_POST['something']) : ''?>
(I use a custom html()
function to escape characters, your mileage may vary)
In PHP 7.0 it's now possible to use Null coalescing operator:
echo "My index value is: " . ($my_array["my_index"] ?? '');
Equals to:
echo "My index value is: " . (isset($my_array["my_index"]) ? $my_array["my_index"] : '');
PHP manual PHP 7.0