PHP Undefined Index

Notice: Undefined variable , Notice: Undefined index , Warning: Undefined array key , and Notice: Undefined offset using PHP

Notice / Warning: Undefined variable

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:

  1. 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'] ?? '';

  1. 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)
  2. Disable E_NOTICE from reporting. A quick way to exclude just E_NOTICE is:

    error_reporting( error_reporting() & ~E_NOTICE )
  3. Suppress the error with the @ operator.

Note: It's strongly recommended to implement just point 1.

Notice: Undefined index / Undefined offset / Warning: Undefined array key

This notice/warning appears when you (or PHP) try to access an undefined index of an array.

Ways to deal with the issue:

  1. 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'] : '';
  2. 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 variable

The 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:

  • Notice: Undefined variable
  • Notice: Undefined Index

PHP Notice: Undefined index

Notice: Undefined index: level in C:\xampp\htdocs\tools\register.php on line 8

Happens when you try to access an array by a key that does not exist in the array.

Hint: to check the exist of the variable do print_r($_POST);

Values for disabled form elements are not passed to the processor
method. The W3C calls this a successful element.(This works similar to
form check boxes that are not checked.)

Instead of disabling the input you rather should add some Javascript to make it unable to edit it like:

var defaultValue = "hello";
element.addEventListener("keyup", function(e){
this.value = defaultValue ;
});

or just use: readonly instaed of disabled or use: style="display: none"

For e.g.:

<input type="text" name="level" placeholder="LEVEL" value="1" style="display: none"/>

(I use this for hidden file upload forms.)

Because I got my coffee already:

Your database connection is (more or less) insecure.
Try this example for a safe connection:

    $db = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", "$db_user", "$db_pass");
$query = $db->prepare("INSERT INTO accounts(username, password) VALUES (?, ?)");
$query->execute(array($username, $password));
$db = null;

How to resolve Undefined index error in PHP

try below where you are displaying the menu

<nav>
<a id="mainpage">Main Page</a>
<?php if (!isset($_SESSION['logged_in'])) { ?>
<a href="login2.php">Login</a>
<a href="register.php">Register</a>
<?php } else { ?>
<a href="post.php">Posting</a>
<a href="#">Members posts</a>
<a href="logout.php" class="outbutton">Logout</a>
<?php } ?>

How can I exclude the bin folder from sourcesafe in a Visual Studio 2008 web application?

  • Right-click the folder in your
    project
  • select "Exclude from project"

Undefined index: usertype' error for $_SESSION

If you are using laravel then you can simply user laravel session method as below,

//For set value in session

$request->session()->put('usertype',$exist[0]->user_type);

//For getting value from session

$request->session()->get('usertype');

//For getting session value in blade file

Session::get('usertype')

Undefined index while trying to work with navigation bar

You need to check page query string is set or not then check further conditions:
so change your $p = $_GET['page']; to :

$p = isset($_GET['page'])?$_GET['page']:"";


Related Topics



Leave a reply



Submit