找到你要的答案

Q:PHP: “Notice: Undefined variable”, “Notice: Undefined index”, and “Notice: Undefined offset” Notice: Undefined variable Notice: Undefined index / Undefined offset $_POST / $_GET / $_SESSION variable

Q:PHP:“注意:定义变量”、“注意:未定义的指标”,和“注意:未定义的偏移” 注意:未定义变量 注意:未定义的索引/未定义的偏移量 _post美元/美元/美元_get _session变量

I am running a PHP script, and keep getting errors like:

Notice: Undefined variable: my_variable_name in C:\wamp\www\mypath\index.php on line 10

Notice: Undefined index: my_index C:\wamp\www\mypath\index.php on line 11

Line 10 and 11 looks like this:

echo "My variable value is: " . $my_variable_name;
echo "My index value is: " . $my_array["my_index"];

What do these errors mean?

Why do they appear all of a sudden? I used to use this script for years and I've never had any problem.

What do I need to do to fix them?

This is a General Reference question for people to link to as duplicate, instead of having to explain the issue over and over again. I feel this is necessary because most real-world answers on this issue are very specific.

Related Meta discussion:

我运行一个PHP脚本,并让错误:

注意:未定义变量: my_variable_name in C:\wamp\www\mypath\index.php on line 10

注意:未定义的指标:my_index C:\ \ \ \ index.php WAMP WWW建立11线

第10和第11号线看起来像这样:

echo "My variable value is: " . $my_variable_name;
echo "My index value is: " . $my_array["my_index"];

这些错误意味着什么?

他们为什么突然出现?我用这个脚本多年,我从来没有任何问题。

我需要做什么来修复它们?

这是一个普遍的参考问题,人们链接到重复,而不是不得不解释一遍又一遍的问题。我觉得这是必要的,因为大多数现实世界的答案在这个问题上是非常具体的。

相关元讨论:

answer1: 回答1:

Notice: 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,"",null.
$o = [];
$var = ["",0,null,1,2,3,$foo,$o['myIndex']];
array_walk($var,function($v){
if(!isset($v) || $v == false) {
echo "empty\n";
}
if(empty($v)) {
echo "empty\n";
}
});

Test the above snippet in PHP Sandbox

Although PHP does not require 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 he will use 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'] : '';
    
  2. 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)
    
  3. Disable E_NOTICE from reporting. A quick way to exclude just E_NOTICE is:

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

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

Notice: Undefined index / Undefined offset

This notice 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. This means they need to be written in uppercase.

Related:

注意:未定义变量

从PHP手册中的大智慧:

依托未初始化变量的默认值是有问题的案件包括一个文件到另一个使用相同的变量名。这是一个重大的安全风险register_globals打开。e_notice水平误差在使用未初始化的变量工作情况发布,但不添加元素的初始化数组的情况。isset()语言构造可用于检测变量是否已经初始化。此外,更理想的是empty()溶液因为它不生成警告或错误消息如果变量未初始化。

从PHP文件,

  • 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,"",null.
$o = [];
$var = ["",0,null,1,2,3,$foo,$o['myIndex']];
array_walk($var,function($v){
if(!isset($v) || $v == false) {
echo "empty\n";
}
if(empty($v)) {
echo "empty\n";
}
});

测试PHP沙箱上面的代码片段

虽然PHP不要求变量声明,它建议,为了避免一些安全漏洞或缺陷,都忘了给一个值给一个变量,他将使用脚本后。在未声明的变量的情况下什么是PHP的问题是一个非常低的水平误差,e_notice,一个甚至没有报道的默认,但手动建议允许在发展。

处理问题的方法:

  1. 建议:声明变量,例如当尝试将一个字符串附加到一个未定义变量时。或使用isset() /!empty()检查是否在引用这些声明,如:

    //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'] : '';
    
  2. 设置一个e_notice自定义错误处理程序和重定向消息从标准输出(也许一个日志文件):

    set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)
    
  3. 禁用e_notice报告。一个快速的方法来排除只是e_notice是:

    error_reporting( error_reporting() & ~E_NOTICE )
    
  4. 用@运算符抑制错误。

注意:强烈建议只执行1点。

注意:未定义的索引/未定义的偏移量

这一公告似乎当你(或PHP)试图访问一个数组定义的指标。

处理问题的方法:

  1. 检查索引是否存在,然后再访问它。这可以用isset()或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. 语言结构list()可能产生这种当它试图访问一个数组的索引不存在:

    list($a, $b) = array(0 => 'a');
    //or
    list($one, $two) = explode(',', 'test string');
    

两个变量用于访问两个数组元素,但只有一个数组元素,索引0,所以这将生成:

注意:未定义偏移量:1

$_POST / $_GET / $_SESSION variable

注意以上工作时经常出现的_post美元美元美元,_get _session。_post美元美元和_get你不得不检查指标存在或不在使用它们之前。_session美元,你必须确保你已经开始session_start(),指数也存在。

注意,所有的3个变量superglobals。这意味着他们需要大写。

相关:

answer2: 回答2:

Try these

Q1: this notice means $varname is not defined at current scope of the script.

Q2: Use of isset(), empty() conditions before using any suspicious variable works well.

// recommended solution
$user_name = $_SESSION['user_name'];
if (empty($user_name)) $user_name = '';

OR 

// just define at the top of the script index.php
$user_name = ''; 
$user_name = $_SESSION['user_name'];

OR 

$user_name = $_SESSION['user_name'];
if (!isset($user_name)) $user_name = '';

QUICK Solution:

// not the best solution, but works
// in your php setting use, it helps hiding site wide notices
error_reporting(E_ALL ^ E_NOTICE);

Note about sessions:

  • When using sessions, session_start(); is required to be placed inside all files using sessions.

  • http://php.net/manual/en/features.sessions.php

试试这些

Q1: this notice means $varname is not defined at current scope of the script.

问:使用isset(),empty()条件之前,使用任何可疑的变好。

// recommended solution
$user_name = $_SESSION['user_name'];
if (empty($user_name)) $user_name = '';

OR 

// just define at the top of the script index.php
$user_name = ''; 
$user_name = $_SESSION['user_name'];

OR 

$user_name = $_SESSION['user_name'];
if (!isset($user_name)) $user_name = '';

快速解决方案:

// not the best solution, but works
// in your php setting use, it helps hiding site wide notices
error_reporting(E_ALL ^ E_NOTICE);

关于会话的说明:

  • 在使用期间,session_start();需要把里面的所有文件使用会话。

  • http://php.net/manual/en/features.sessions.php

answer3: 回答3:

A (often discouraged) alternative is the error suppression operator @. It is a specific language construct to shut down undesired notices and warnings, but should be used with care.

First, it incurs a microperformance penalty over using isset. That's not measurable in real world applications, but should be considered in data heavy iterations. Secondly it might obstruct debugging, but at the same time suppressed errors are in fact passed on to custom error handlers (unlike isset decorated expressions).

一个(通常沮丧)的选择是错误抑制操作符@。它是一个特定的语言结构,关闭不需要的通知和警告,但应小心使用。

首先,它会导致一个microperformance处罚使用isset。这在现实世界的应用中是不可测量的,但应考虑在数据重迭代。其次,它可能会妨碍调试,同时抑制错误实际上是传递给自定义错误处理程序(不像isset装饰表达式)。

php  arrays  variables  warnings  undefined-index