PHP:“注意:未定义变量”、“注意:未定义索引”和“注意:未定义偏移量”

时间:2022-10-17 12:17:56

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

我正在运行一个PHP脚本,并不断地收到错误,比如:

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

注意:未定义的变量:my_variable_name in C:\wamp\www\mypath\index。php的地铁十号线

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

注意:未定义索引:my_index C:\wamp\www\mypath\index。php在第11行

Line 10 and 11 looks like this:

第10行和第11行是这样的:

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:

相关元讨论:

24 个解决方案

#1


854  

Notice: Undefined variable

From the vast wisdom of the PHP Manual:

来自PHP手册的巨大智慧:

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.

如果将一个文件包含到使用相同变量名的另一个文件中,那么依赖未初始化变量的默认值是有问题的。打开register_globals也会带来很大的安全风险。在处理未初始化的变量时,会发出E_NOTICE级别错误,但在向未初始化的数组添加元素时则不会。可以使用isset()语言构造来检测变量是否已经初始化。此外,更理想的是empty()的解决方案,因为如果变量没有初始化,它不会生成警告或错误消息。

From PHP documentation:

从PHP文档:

No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.

如果变量不存在,则不会生成警告。这意味着empty()本质上相当于!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.

这意味着您只能使用empty()来确定是否设置了该变量,此外,它将根据下面的0、"、空来检查该变量。

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

在3v4l.org在线PHP编辑器中测试上述代码片段

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.

尽管PHP不需要变量声明,但它确实推荐使用它,以避免某些安全漏洞或bug,在这些漏洞中,我们可能会忘记为稍后在脚本中使用的变量赋值。PHP在未声明变量的情况下所做的是发出一个非常低的级别错误E_NOTICE,这个错误在默认情况下甚至没有报告,但是手册建议在开发过程中允许这样做。

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:

    建议:声明您的变量,例如,当您尝试将一个字符串追加到一个未定义的变量时。或使用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'] : '';
    

    This has become much cleaner as of PHP 7.0, now you can use the null coalesce operator:

    现在,您可以使用null coalesce操作符:

    // Null coalesce operator - No need to explicitly initialize the variable.
    $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):

    为E_NOTICE设置一个自定义错误处理程序,并将消息重定向到标准输出(可能是日志文件):

    set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)
    
  3. Disable E_NOTICE from reporting. A quick way to exclude just E_NOTICE is:

    禁用E_NOTICE报道。一个快速排除E_NOTICE的方法是:

    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.

当您(或PHP)试图访问数组的未定义索引时,将出现此通知。

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()或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:

两个变量用于访问两个数组元素,但是只有一个数组元素,索引0,因此会生成:

Notice: Undefined offset: 1

注意:未定义的补偿: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.

当使用$_POST、$_GET或$_SESSION时,上面的通知经常出现。对于$_POST和$_GET,您只需在使用它们之前检查索引是否存在。对于$_SESSION,您必须确保会话以session_start()开头,并且索引也存在。

Also note that all 3 variables are superglobals and are uppercase.

还要注意,所有3个变量都是超全局变量,都是大写的。

Related:

相关:

#2


103  

Try these

试试这些

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

Q1:此通知意味着$varname在脚本当前范围内没有定义。

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

Q2:在使用任何可疑变量之前,使用isset()、empty()条件是有效的。

// recommended solution
$user_name = "";
if (! empty($_SESSION['user_name'])) {
     $user_name = $_SESSION['user_name'];
}

Or, as a quick and dirty 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.

    当使用会话,session_start();需要使用会话将文件放在所有文件中。

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

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

#3


43  

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).

首先,它会对使用isset造成微性能损失。这在实际应用程序中是不可度量的,但是应该在数据重迭代中考虑。其次,它可能会阻碍调试,但与此同时,隐藏的错误实际上会传递给自定义错误处理程序(不像isset修饰的表达式)。

#4


34  

It means you are testing, evaluating, or printing a variable that you have not yet assigned anything to. It means you either have a typo, or you need to check that the variable was initialized to something first. Check your logic paths, it may be set in one path but not in another.

这意味着您正在测试、评估或打印一个尚未分配任何内容的变量。这意味着您要么有一个输入错误,要么需要检查变量是否被初始化为某样东西。检查逻辑路径,它可以在一条路径中设置,但不能在另一条路径中设置。

#5


31  

Generally because of "bad programming", and a possibility for mistakes now or later.

通常是因为“糟糕的编程”,以及现在或以后出现错误的可能性。

  1. If it's a mistake, make a proper assignment to the variable first: $varname=0;
  2. 如果是错误的,首先对变量进行适当的赋值:$varname=0;
  3. If it really is only defined sometimes, test for it: if (isset($varname)), before using it
  4. 如果它只是有时定义的,那么在使用它之前测试一下:If (isset($varname))
  5. If it's because you spelled it wrong, just correct that
  6. 如果是因为你拼错了,那就纠正它
  7. Maybe even turn of the warnings in you PHP-settings
  8. 甚至可能在你的php设置中使用警告

#6


30  

I didn't want to disable notice because it's helpful, but wanted to avoid too much typing.

我不想禁用通知,因为它很有用,但我想避免输入太多。

My solution was this function:

我的解决方案是这个函数:

function ifexists($varname)
{
  return(isset($$varname)?$varname:null);
}

So if I want to reference to $name and echo if exists, I simply write:

因此,如果我想引用$name和echo(如果存在的话),我只需写:

<?=ifexists('name')?>

For array elements:

数组元素:

function ifexistsidx($var,$index)
{
  return(isset($var[$index])?$var[$index]:null);
}

In page if I want to refer to $_REQUEST['name']:

在页面中,如果我想引用$_REQUEST['name']:

<?=ifexistsidx($_REQUEST,'name')?>

#7


24  

The best way for getting input string is:

获取输入字符串的最佳方法是:

$value = filter_input(INPUT_POST, 'value');

This one-liner is almost equivalent to:

这一行几乎相当于:

if (!isset($_POST['value'])) {
    $value = null;
} elseif (is_array($_POST['value'])) {
    $value = false;
} else {
    $value = $_POST['value'];
}

If you absolutely want string value, just like:

如果你绝对想要字符串值,就像:

$value = (string)filter_input(INPUT_POST, 'value');

#8


23  

Its because the variable '$user_location' is not getting defined. If you are using any if loop inside which you are declaring the '$user_location' variable then you must also have an else loop and define the same. For example:

因为变量'$user_location'没有被定义。如果您正在使用任何If循环来声明'$user_location'变量,那么您还必须有一个else循环并定义相同的循环。例如:

$a=10;
if($a==5) { $user_location='Paris';} else { }
echo $user_location;

The above code will create error as The if loop is not satisfied and in the else loop '$user_location' was not defined. Still PHP was asked to echo out the variable. So to modify the code you must do the following:

上面的代码将创建错误,因为if循环不满足,在else循环“$user_location”中没有定义。仍然要求PHP回显变量。因此,要修改代码,您必须执行以下操作:

$a=10;
if($a==5) { $user_location='Paris';} else { $user_location='SOMETHING OR BLANK'; }
echo $user_location;

#9


22  

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

在回答“为什么它们突然出现?”我使用这个脚本很多年了,我从来没有遇到过任何问题。

It is very common for most sites to operate under the "default" error reporting of "Show all errors, but not 'notices' and 'deprecated'". This will be set in php.ini and apply to all sites on the server. This means that those "notices" used in the examples will be suppressed (hidden) while other errors, considered more critical, will be shown/recorded.

大多数站点在“显示所有错误,但不显示‘通知’和‘已弃用’”的“默认”错误报告下操作是很常见的。这将在php中设置。并应用于服务器上的所有站点。这意味着在示例中使用的那些“通知”将被隐藏(隐藏),而其他被认为更重要的错误将被显示/记录。

The other critical setting is the errors can be hidden (i.e. display_errors set to "off" or "syslog").

另一个关键设置是可以隐藏错误(例如,将display_errors设置为“off”或“syslog”)。

What will have happened in this case is that either the error_reporting was changed to also show notices (as per examples) and/or that the settings were changed to display_errors on screen (as opposed to suppressing them/logging them).

在这种情况下会发生的情况是,error_reporting被更改为也显示通知(如每个示例)和/或将设置更改为屏幕上的display_errors(而不是抑制它们/记录它们)。

Why have they changed?

他们为什么改变了?

The obvious/simplest answer is that someone adjusted either of these settings in php.ini, or an upgraded version of PHP is now using a different php.ini from before. That's the first place to look.

最明显/最简单的答案是,有人在php中调整了其中任何一个设置。ini或升级版的PHP现在使用不同的PHP。ini之前。这是第一个要看的地方。

However it is also possible to override these settings in

但是也可以在其中覆盖这些设置

  • .htconf (webserver configuration, including vhosts and sub-configurations)*
  • .htconf (webserver配置,包括vhosts和子配置)*
  • .htaccess
  • . htaccess
  • in php code itself
  • 在php代码本身

and any of these could also have been changed.

任何一个都可以被改变。

There is also the added complication that the web server configuration can enable/disable .htaccess directives, so if you have directives in .htaccess that suddenly start/stop working then you need to check for that.

web服务器配置还可以启用/禁用.htaccess指令,因此如果.htaccess中的指令突然开始/停止工作,那么需要检查它。

(.htconf / .htaccess assume you're running as apache. If running command line this won't apply; if running IIS or other webserver then you'll need to check those configs accordingly)

(。htconf / .htaccess假定您是作为apache运行的。如果运行命令行,这将不适用;如果运行IIS或其他webserver,则需要相应地检查这些配置)

Summary

总结

  • Check error_reporting and display_errors php directives in php.ini has not changed, or that you're not using a different php.ini from before.
  • 在php中检查error_reporting和display_errors php指令。ini没有更改,或者您没有使用不同的php。ini之前。
  • Check error_reporting and display_errors php directives in .htconf (or vhosts etc) have not changed
  • 检查.htconf(或vhosts等)中的error_reporting和display_errors php指令没有更改
  • Check error_reporting and display_errors php directives in .htaccess have not changed
  • 检查.htaccess中的error_reporting和display_errors php指示没有更改
  • If you have directive in .htaccess, check if they are still permitted in the .htconf file
  • 如果在.htaccess中有指令,请检查它们在.htconf文件中是否仍然被允许
  • Finally check your code; possibly an unrelated library; to see if error_reporting and display_errors php directives have been set there.
  • 最后检查你的代码;可能一个不相关的库;查看是否在那里设置了error_reporting和display_errors php指示。

#10


16  

the quick fix is to assign your variable to null at the top of your code

快速解决方案是将变量赋值为null

$user_location = null;

#11


14  

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)

(我使用自定义的html()函数来转义字符,您的里数可能不同)

#12


12  

I use all time own useful function exst() which automatically declare variables.

我一直使用自己有用的函数exst()自动声明变量。

Your code will be -

您的代码将是-

$greeting = "Hello, ".exst($user_name, 'Visitor')." from ".exst($user_location);


/** 
 * Function exst() - Checks if the variable has been set 
 * (copy/paste it in any place of your code)
 * 
 * If the variable is set and not empty returns the variable (no transformation)
 * If the variable is not set or empty, returns the $default value
 *
 * @param  mixed $var
 * @param  mixed $default
 * 
 * @return mixed 
 */

function exst( & $var, $default = "")
{
    $t = "";
    if ( !isset($var)  || !$var ) {
        if (isset($default) && $default != "") $t = $default;
    }
    else  {  
        $t = $var;
    }
    if (is_string($t)) $t = trim($t);
    return $t;
}

#13


12  

In a very Simple Language.
The mistake is you are using a variable $user_location which is not defined by you earlier and it doesn't have any value So I recommend you to please declare this variable before using it, For Example:

用一种非常简单的语言。错误在于您使用的变量$user_location之前没有定义它没有任何值,所以我建议您在使用它之前先声明这个变量,例如:


$user_location = '';
Or
$user_location = 'Los Angles';
This is a very common error you can face.So don't worry just declare the variable and Enjoy Coding.

#14


11  

In PHP 7.0 it's now possible to use Null coalescing operator:

在PHP 7.0中,现在可以使用空合并运算符:

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

PHP手册PHP 7.0

#15


7  

WHY IS THIS HAPPENING?

Over time, PHP has become a more security-focused language. Settings which used to be turned off by default are now turned on by default. A perfect example of this is E_STRICT, which became turned on by default as of PHP 5.4.0.

随着时间的推移,PHP已经成为一种更加关注安全的语言。以前默认关闭的设置现在默认打开。E_STRICT就是一个很好的例子,它在PHP 5.4.0中默认打开。

Furthermore, according to PHP documentation, by defualt, E_NOTICE is disabled in php.ini. PHP docs recommend turning it on for debugging purposes. However, when I download PHP from the Ubuntu repository–and from BitNami's Windows stack–I see something else.

此外,根据PHP文档,defualt在PHP .ini中禁用了E_NOTICE。PHP文档建议为调试目的打开它。然而,当我从Ubuntu储存库和BitNami的Windows堆叠中下载PHP时,我看到了其他东西。

; Common Values:
;   E_ALL (Show all errors, warnings and notices including coding standards.)
;   E_ALL & ~E_NOTICE  (Show all errors, except for notices)
;   E_ALL & ~E_NOTICE & ~E_STRICT  (Show all errors, except for notices and coding standards warnings.)
;   E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR  (Show only errors)
; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
; Development Value: E_ALL
; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
; http://php.net/error-reporting
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT

Notice that error_reporting is actually set to the production value by default, not to the "default" value by default. This is somewhat confusing and is not documented outside of php.ini, so I have not validated this on other distributions.

注意,error_reporting实际上是默认设置为生产值,而不是默认设置为“默认”值。这有点令人困惑,在php之外没有记录。ini,所以我没有在其他发行版中验证这个。

To answer your question, however, this error pops up now when it did not pop up before because:

然而,要回答你的问题,这个错误在以前没有出现时就出现了,因为:

  1. You installed PHP and the new default settings are somewhat poorly documented, but do not exclude E_NOTICE.

    您已经安装了PHP,新的默认设置的文档比较少,但是不排除E_NOTICE。

  2. E_NOTICE warnings like undefined variables and undefined indexes actually help to make your code cleaner and safer. I can tell you that, years ago, keeping E_NOTICE enabled forced me to declare my variables. It made it a LOT easier to learn C, where not declaring variables is much bigger of a nuisance.

    E_NOTICE警告(如未定义的变量和未定义的索引)实际上有助于使代码更简洁、更安全。我可以告诉你,多年前,保持E_NOTICE使我不得不声明我的变量。它使学习C变得容易得多,在这里,不声明变量要大得多。

WHAT CAN I DO ABOUT IT?

  1. Turn off E_NOTICE by copying the "Default value" E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED and replacing it with what is currently uncommented after the equals sign in error_reporting =. Restart Apache, or PHP if using CGI or FPM. Make sure you are editing the "right" php.ini. The correct one will be Apache if you are running PHP with Apache, fpm or php-fpm if running PHP-FPM, cgi if running PHP-CGI, etc. This is not the recommended method, but if you have legacy code that's going to be exceedingly difficult to edit, then it might be your best bet.

    通过复制“默认值”E_ALL & ~E_NOTICE & ~E_STRICT & ~E_STRICT & ~E_DEPRECATED并将其替换为在error_reporting =中等号后当前未注释的内容,从而关闭E_NOTICE。如果使用CGI或FPM,则重新启动Apache或PHP。确保你正在编辑“正确的”ph .ini。正确的将Apache如果您正在运行PHP和Apache,fpm或php-fpm如果php-fpm运行,运行cgi如果PHP-CGI,等等。这是不推荐的方法,但是如果你有遗留代码将会极其困难的编辑,那么它可能是你最好的选择。

  2. Turn off E_NOTICE on the file or folder level. This might be preferable if you have some legacy code but want to do things the "right" way otherwise. To do this, you should consult Apache2, nginx, or whatever your server of choice is. In Apache, you would use php_value inside of <Directory>.

    关闭文件或文件夹级别的E_NOTICE。如果您有一些遗留代码,但是希望以“正确”的方式进行操作,那么这样做可能更好。为此,您应该咨询Apache2、nginx或任何您选择的服务器。在Apache中,您将在 中使用php_value。

  3. Rewrite your code to be cleaner. If you need to do this while moving to a production environment, or don't want someone to see your errors, make sure you are disabling any display of errors, and only logging your errors (see display_errors and log_errors in php.ini and your server settings).

    将代码重写为更简洁。如果在迁移到生产环境时需要这样做,或者不希望有人看到您的错误,请确保禁用了任何错误显示,并且只记录错误(请参见php中的display_errors和log_errors)。ini和您的服务器设置)。

To expand on option 3: This is the ideal. If you can go this route, you should. If you are not going this route initially, consider moving this route eventually by testing your code in a development environment. While you're at it, get rid of ~E_STRICT and ~E_DEPRECATED to see what might go wrong in the future. You're going to see a LOT of unfamiliar errors, but it's going to stop you from having any unpleasant problems when you need to upgrade PHP in the future.

扩展选项3:这是理想的。如果你能走这条路,你应该走。如果您最初不走这条路线,可以考虑在开发环境中测试代码,最终移动这条路线。当您使用它的时候,请去掉~E_STRICT和~E_DEPRECATED,看看将来会出现什么问题。您将会看到许多不熟悉的错误,但是当您将来需要升级PHP时,它将阻止您遇到任何不愉快的问题。

WHAT DO THE ERRORS MEAN?

Undefined variable: my_variable_name - This occurs when a variable has not been defined before use. When the PHP script is executed, it internally just assumes a null value. However, in which scenario would you need to check a variable before it was defined? Ultimately, this is an argument for "sloppy code". As a developer, I can tell you that I love it when I see an open source project where variables are defined as high up in their scopes as they can be defined. It makes it easier to tell what variables are going to pop up in the future, and makes it easier to read/learn the code.

未定义变量:my_variable_name—当变量在使用前没有定义时发生。当执行PHP脚本时,它在内部假设一个空值。但是,在这种情况下,您需要在变量定义之前检查一个变量吗?归根结底,这是“草率代码”的论据。作为一名开发人员,我可以告诉您,当我看到一个开源项目时,我很喜欢它,在这个项目中,变量在它们的作用域中定义得尽可能高。它使我们更容易知道将来会出现什么变量,也使我们更容易阅读/学习代码。

function foo()
{
    $my_variable_name = '';

    //....

    if ($my_variable_name) {
        // perform some logic
    }
}

Undefined index: my_index - This occurs when you try to access a value in an array and it does not exist. To prevent this error, perform a conditional check.

未定义索引:my_index——当您试图访问数组中的值时,它不存在。要防止此错误,请执行条件检查。

// verbose way - generally better
if (isset($my_array['my_index'])) {
    echo "My index value is: " . $my_array['my_index'];
}

// non-verbose ternary example - I use this sometimes for small rules.
$my_index_val = isset($my_array['my_index'])?$my_array['my_index']:'(undefined)';
echo "My index value is: " . $my_index_val;   

Another option is to declare an empty array at the top of your function. This is not always possible.

另一个选项是在函数的顶部声明一个空数组。这不总是可能的。

$my_array = array(
    'my_index' => ''
);

//...

$my_array['my_index'] = 'new string';

(additional tip)

  • When I was encountering these and other issues, I used NetBeans IDE (free) and it gave me a host of warnings and notices. Some of them offer very helpful tips. This is not a requirement, and I don't use IDEs anymore except for large projects. I'm more of a vim person these days :).
  • 当我遇到这些问题和其他问题时,我使用NetBeans IDE(免费),它给了我大量的警告和通知。他们中的一些人提供了非常有用的建议。这不是一个需求,除了大型项目之外,我不再使用ide。现在我更像一个生气勃勃的人。

#16


6  

why not keep things simple?

为什么不把事情简单化呢?

<?php
error_reporting(E_ALL); // making sure all notices are on

function idxVal(&$var, $default = null) {
         return empty($var) ? $var = $default : $var;
  }

echo idxVal($arr['test']);         // returns null without any notice
echo idxVal($arr['hey ho'], 'yo'); // returns yo and assigns it to array index, nice

?>

#17


5  

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);

#18


3  

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:

没有明确的答案,但这里有一些可能的解释,为什么设置可以“突然”改变:

  1. You have upgraded PHP to a newer version which can have other defaults for error_reporting, display_errors or other relevant settings.

    您已经将PHP升级到一个更新的版本,该版本可以有error_reporting、display_errors或其他相关设置的其他默认值。

  2. 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)

    您已经删除或引入了一些代码(可能在依赖项中),在运行时使用ini_set()或error_reporting()来设置相关设置(在代码中搜索这些设置)

  3. You changed the webserver configuration (assuming apache here): .htaccess files and vhost configurations can also manipulate php settings.

    您更改了webserver配置(假设这里是apache): .htaccess文件和vhost配置也可以操作php设置。

  4. 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.

    通常通知不会显示/报告(参见PHP手册),所以在设置服务器时,PHP可能会出现。由于某些原因(文件权限?),ini文件无法被加载,您处于默认设置中。稍后,“bug”被解决(纯属偶然),现在它可以加载正确的php。包含error_reporting设置为显示通知的ini文件。

#19


3  

Another reason why an undefined index notice will be thrown, would be that a column was omitted from a database query.

将抛出未定义索引通知的另一个原因是,在数据库查询中省略了列。

I.e.:

例如:

$query = "SELECT col1 FROM table WHERE col_x = ?";

Then trying to access more columns/rows inside a loop.

然后尝试访问循环中的更多列/行。

I.e.:

例如:

print_r($row['col1']);
print_r($row['col2']); // undefined index thrown

or in a while loop:

或者在一段时间内循环:

while( $row = fetching_function($query) ) {

    echo $row['col1'];
    echo "<br>";
    echo $row['col2']; // undefined index thrown
    echo "<br>";
    echo $row['col3']; // undefined index thrown

}

Something else that needs to be noted is that on a *NIX OS and Mac OS X, things are case-sensitive.

需要注意的是,在*NIX操作系统和Mac OS X上,事物是区分大小写的。

Consult the followning Q&A's on Stack:

请参阅以下堆叠上的问答:

#20


2  

If working with classes you need to make sure you reference member variables using $this:

如果使用类,您需要确保使用$this引用成员变量:

class Person
{
    protected $firstName;
    protected $lastName;

    public function setFullName($first, $last)
    {
        // Correct
        $this->firstName = $first;

        // Incorrect
        $lastName = $last;

        // Incorrect
        $this->$lastName = $last;
    }
}

#21


1  

Probably you were using old PHP version until and now upgraded PHP thats the reason it was working without any error till now from years. until PHP4 there was no error if you are using variable without defining it but as of PHP5 onwards it throws errors for codes like mentioned in question.

可能您一直在使用旧的PHP版本,直到现在才对PHP进行升级,这就是为什么它从几年以来一直没有出现任何错误。在PHP4之前,如果你使用变量而不定义它,就不会出现错误,但是当PHP5以后,它会为问题中提到的代码抛出错误。

#22


1  

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.

在处理文件时,需要适当的封装类型和POST方法,如果表单中没有包含这两个方法,则该方法将触发一个未定义的索引通知。

The manual states the following basic syntax:

手册规定了以下基本语法:

HTML

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

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

参考:

#23


0  

Those notices are because you don't have the used variable defined and my_index key was not present into $my_array variable.

这些注意事项是因为您没有定义使用的变量,my_index键没有出现在$my_array变量中。

Those notices were triggered every time, because your code is not correct, but probably you didn't have the reporting of notices on.

这些通知每次都会被触发,因为您的代码不正确,但是您可能没有通知的报告。

Solve the bugs:

解决错误:

$my_variable_name = "Variable name"; // defining variable
echo "My variable value is: " . $my_variable_name;

if(isset($my_array["my_index"])){
    echo "My index value is: " . $my_array["my_index"]; // check if my_index is set 
}

Another way to get this out:

另一种解决方法是:

ini_set("error_reporting", false)

#24


0  

In PHP you need fist to define the variable after that you can use it.
We can check variable is defined or not in very efficient way!.

在PHP中,需要首先定义变量,然后才能使用它。我们可以用非常有效的方式检查变量是否被定义!

//If you only want to check variable has value and value has true and false value.
//But variable must be defined first.

if($my_variable_name){

}

//If you want to check variable is define or undefine
//Isset() does not check that variable has true or false value
//But it check null value of variable
if(isset($my_variable_name)){

}

Simple Explanation

简单的解释

//It will work with :- true,false,NULL
$defineVarialbe = false;
if($defineVarialbe){
    echo "true";
}else{
    echo "false";
}

//It will check variable is define or not and variable has null value.
if(isset($unDefineVarialbe)){
    echo "true";
}else{
    echo "false";
}

#1


854  

Notice: Undefined variable

From the vast wisdom of the PHP Manual:

来自PHP手册的巨大智慧:

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.

如果将一个文件包含到使用相同变量名的另一个文件中,那么依赖未初始化变量的默认值是有问题的。打开register_globals也会带来很大的安全风险。在处理未初始化的变量时,会发出E_NOTICE级别错误,但在向未初始化的数组添加元素时则不会。可以使用isset()语言构造来检测变量是否已经初始化。此外,更理想的是empty()的解决方案,因为如果变量没有初始化,它不会生成警告或错误消息。

From PHP documentation:

从PHP文档:

No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.

如果变量不存在,则不会生成警告。这意味着empty()本质上相当于!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.

这意味着您只能使用empty()来确定是否设置了该变量,此外,它将根据下面的0、"、空来检查该变量。

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

在3v4l.org在线PHP编辑器中测试上述代码片段

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.

尽管PHP不需要变量声明,但它确实推荐使用它,以避免某些安全漏洞或bug,在这些漏洞中,我们可能会忘记为稍后在脚本中使用的变量赋值。PHP在未声明变量的情况下所做的是发出一个非常低的级别错误E_NOTICE,这个错误在默认情况下甚至没有报告,但是手册建议在开发过程中允许这样做。

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:

    建议:声明您的变量,例如,当您尝试将一个字符串追加到一个未定义的变量时。或使用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'] : '';
    

    This has become much cleaner as of PHP 7.0, now you can use the null coalesce operator:

    现在,您可以使用null coalesce操作符:

    // Null coalesce operator - No need to explicitly initialize the variable.
    $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):

    为E_NOTICE设置一个自定义错误处理程序,并将消息重定向到标准输出(可能是日志文件):

    set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)
    
  3. Disable E_NOTICE from reporting. A quick way to exclude just E_NOTICE is:

    禁用E_NOTICE报道。一个快速排除E_NOTICE的方法是:

    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.

当您(或PHP)试图访问数组的未定义索引时,将出现此通知。

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()或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:

两个变量用于访问两个数组元素,但是只有一个数组元素,索引0,因此会生成:

Notice: Undefined offset: 1

注意:未定义的补偿: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.

当使用$_POST、$_GET或$_SESSION时,上面的通知经常出现。对于$_POST和$_GET,您只需在使用它们之前检查索引是否存在。对于$_SESSION,您必须确保会话以session_start()开头,并且索引也存在。

Also note that all 3 variables are superglobals and are uppercase.

还要注意,所有3个变量都是超全局变量,都是大写的。

Related:

相关:

#2


103  

Try these

试试这些

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

Q1:此通知意味着$varname在脚本当前范围内没有定义。

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

Q2:在使用任何可疑变量之前,使用isset()、empty()条件是有效的。

// recommended solution
$user_name = "";
if (! empty($_SESSION['user_name'])) {
     $user_name = $_SESSION['user_name'];
}

Or, as a quick and dirty 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.

    当使用会话,session_start();需要使用会话将文件放在所有文件中。

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

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

#3


43  

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).

首先,它会对使用isset造成微性能损失。这在实际应用程序中是不可度量的,但是应该在数据重迭代中考虑。其次,它可能会阻碍调试,但与此同时,隐藏的错误实际上会传递给自定义错误处理程序(不像isset修饰的表达式)。

#4


34  

It means you are testing, evaluating, or printing a variable that you have not yet assigned anything to. It means you either have a typo, or you need to check that the variable was initialized to something first. Check your logic paths, it may be set in one path but not in another.

这意味着您正在测试、评估或打印一个尚未分配任何内容的变量。这意味着您要么有一个输入错误,要么需要检查变量是否被初始化为某样东西。检查逻辑路径,它可以在一条路径中设置,但不能在另一条路径中设置。

#5


31  

Generally because of "bad programming", and a possibility for mistakes now or later.

通常是因为“糟糕的编程”,以及现在或以后出现错误的可能性。

  1. If it's a mistake, make a proper assignment to the variable first: $varname=0;
  2. 如果是错误的,首先对变量进行适当的赋值:$varname=0;
  3. If it really is only defined sometimes, test for it: if (isset($varname)), before using it
  4. 如果它只是有时定义的,那么在使用它之前测试一下:If (isset($varname))
  5. If it's because you spelled it wrong, just correct that
  6. 如果是因为你拼错了,那就纠正它
  7. Maybe even turn of the warnings in you PHP-settings
  8. 甚至可能在你的php设置中使用警告

#6


30  

I didn't want to disable notice because it's helpful, but wanted to avoid too much typing.

我不想禁用通知,因为它很有用,但我想避免输入太多。

My solution was this function:

我的解决方案是这个函数:

function ifexists($varname)
{
  return(isset($$varname)?$varname:null);
}

So if I want to reference to $name and echo if exists, I simply write:

因此,如果我想引用$name和echo(如果存在的话),我只需写:

<?=ifexists('name')?>

For array elements:

数组元素:

function ifexistsidx($var,$index)
{
  return(isset($var[$index])?$var[$index]:null);
}

In page if I want to refer to $_REQUEST['name']:

在页面中,如果我想引用$_REQUEST['name']:

<?=ifexistsidx($_REQUEST,'name')?>

#7


24  

The best way for getting input string is:

获取输入字符串的最佳方法是:

$value = filter_input(INPUT_POST, 'value');

This one-liner is almost equivalent to:

这一行几乎相当于:

if (!isset($_POST['value'])) {
    $value = null;
} elseif (is_array($_POST['value'])) {
    $value = false;
} else {
    $value = $_POST['value'];
}

If you absolutely want string value, just like:

如果你绝对想要字符串值,就像:

$value = (string)filter_input(INPUT_POST, 'value');

#8


23  

Its because the variable '$user_location' is not getting defined. If you are using any if loop inside which you are declaring the '$user_location' variable then you must also have an else loop and define the same. For example:

因为变量'$user_location'没有被定义。如果您正在使用任何If循环来声明'$user_location'变量,那么您还必须有一个else循环并定义相同的循环。例如:

$a=10;
if($a==5) { $user_location='Paris';} else { }
echo $user_location;

The above code will create error as The if loop is not satisfied and in the else loop '$user_location' was not defined. Still PHP was asked to echo out the variable. So to modify the code you must do the following:

上面的代码将创建错误,因为if循环不满足,在else循环“$user_location”中没有定义。仍然要求PHP回显变量。因此,要修改代码,您必须执行以下操作:

$a=10;
if($a==5) { $user_location='Paris';} else { $user_location='SOMETHING OR BLANK'; }
echo $user_location;

#9


22  

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

在回答“为什么它们突然出现?”我使用这个脚本很多年了,我从来没有遇到过任何问题。

It is very common for most sites to operate under the "default" error reporting of "Show all errors, but not 'notices' and 'deprecated'". This will be set in php.ini and apply to all sites on the server. This means that those "notices" used in the examples will be suppressed (hidden) while other errors, considered more critical, will be shown/recorded.

大多数站点在“显示所有错误,但不显示‘通知’和‘已弃用’”的“默认”错误报告下操作是很常见的。这将在php中设置。并应用于服务器上的所有站点。这意味着在示例中使用的那些“通知”将被隐藏(隐藏),而其他被认为更重要的错误将被显示/记录。

The other critical setting is the errors can be hidden (i.e. display_errors set to "off" or "syslog").

另一个关键设置是可以隐藏错误(例如,将display_errors设置为“off”或“syslog”)。

What will have happened in this case is that either the error_reporting was changed to also show notices (as per examples) and/or that the settings were changed to display_errors on screen (as opposed to suppressing them/logging them).

在这种情况下会发生的情况是,error_reporting被更改为也显示通知(如每个示例)和/或将设置更改为屏幕上的display_errors(而不是抑制它们/记录它们)。

Why have they changed?

他们为什么改变了?

The obvious/simplest answer is that someone adjusted either of these settings in php.ini, or an upgraded version of PHP is now using a different php.ini from before. That's the first place to look.

最明显/最简单的答案是,有人在php中调整了其中任何一个设置。ini或升级版的PHP现在使用不同的PHP。ini之前。这是第一个要看的地方。

However it is also possible to override these settings in

但是也可以在其中覆盖这些设置

  • .htconf (webserver configuration, including vhosts and sub-configurations)*
  • .htconf (webserver配置,包括vhosts和子配置)*
  • .htaccess
  • . htaccess
  • in php code itself
  • 在php代码本身

and any of these could also have been changed.

任何一个都可以被改变。

There is also the added complication that the web server configuration can enable/disable .htaccess directives, so if you have directives in .htaccess that suddenly start/stop working then you need to check for that.

web服务器配置还可以启用/禁用.htaccess指令,因此如果.htaccess中的指令突然开始/停止工作,那么需要检查它。

(.htconf / .htaccess assume you're running as apache. If running command line this won't apply; if running IIS or other webserver then you'll need to check those configs accordingly)

(。htconf / .htaccess假定您是作为apache运行的。如果运行命令行,这将不适用;如果运行IIS或其他webserver,则需要相应地检查这些配置)

Summary

总结

  • Check error_reporting and display_errors php directives in php.ini has not changed, or that you're not using a different php.ini from before.
  • 在php中检查error_reporting和display_errors php指令。ini没有更改,或者您没有使用不同的php。ini之前。
  • Check error_reporting and display_errors php directives in .htconf (or vhosts etc) have not changed
  • 检查.htconf(或vhosts等)中的error_reporting和display_errors php指令没有更改
  • Check error_reporting and display_errors php directives in .htaccess have not changed
  • 检查.htaccess中的error_reporting和display_errors php指示没有更改
  • If you have directive in .htaccess, check if they are still permitted in the .htconf file
  • 如果在.htaccess中有指令,请检查它们在.htconf文件中是否仍然被允许
  • Finally check your code; possibly an unrelated library; to see if error_reporting and display_errors php directives have been set there.
  • 最后检查你的代码;可能一个不相关的库;查看是否在那里设置了error_reporting和display_errors php指示。

#10


16  

the quick fix is to assign your variable to null at the top of your code

快速解决方案是将变量赋值为null

$user_location = null;

#11


14  

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)

(我使用自定义的html()函数来转义字符,您的里数可能不同)

#12


12  

I use all time own useful function exst() which automatically declare variables.

我一直使用自己有用的函数exst()自动声明变量。

Your code will be -

您的代码将是-

$greeting = "Hello, ".exst($user_name, 'Visitor')." from ".exst($user_location);


/** 
 * Function exst() - Checks if the variable has been set 
 * (copy/paste it in any place of your code)
 * 
 * If the variable is set and not empty returns the variable (no transformation)
 * If the variable is not set or empty, returns the $default value
 *
 * @param  mixed $var
 * @param  mixed $default
 * 
 * @return mixed 
 */

function exst( & $var, $default = "")
{
    $t = "";
    if ( !isset($var)  || !$var ) {
        if (isset($default) && $default != "") $t = $default;
    }
    else  {  
        $t = $var;
    }
    if (is_string($t)) $t = trim($t);
    return $t;
}

#13


12  

In a very Simple Language.
The mistake is you are using a variable $user_location which is not defined by you earlier and it doesn't have any value So I recommend you to please declare this variable before using it, For Example:

用一种非常简单的语言。错误在于您使用的变量$user_location之前没有定义它没有任何值,所以我建议您在使用它之前先声明这个变量,例如:


$user_location = '';
Or
$user_location = 'Los Angles';
This is a very common error you can face.So don't worry just declare the variable and Enjoy Coding.

#14


11  

In PHP 7.0 it's now possible to use Null coalescing operator:

在PHP 7.0中,现在可以使用空合并运算符:

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

PHP手册PHP 7.0

#15


7  

WHY IS THIS HAPPENING?

Over time, PHP has become a more security-focused language. Settings which used to be turned off by default are now turned on by default. A perfect example of this is E_STRICT, which became turned on by default as of PHP 5.4.0.

随着时间的推移,PHP已经成为一种更加关注安全的语言。以前默认关闭的设置现在默认打开。E_STRICT就是一个很好的例子,它在PHP 5.4.0中默认打开。

Furthermore, according to PHP documentation, by defualt, E_NOTICE is disabled in php.ini. PHP docs recommend turning it on for debugging purposes. However, when I download PHP from the Ubuntu repository–and from BitNami's Windows stack–I see something else.

此外,根据PHP文档,defualt在PHP .ini中禁用了E_NOTICE。PHP文档建议为调试目的打开它。然而,当我从Ubuntu储存库和BitNami的Windows堆叠中下载PHP时,我看到了其他东西。

; Common Values:
;   E_ALL (Show all errors, warnings and notices including coding standards.)
;   E_ALL & ~E_NOTICE  (Show all errors, except for notices)
;   E_ALL & ~E_NOTICE & ~E_STRICT  (Show all errors, except for notices and coding standards warnings.)
;   E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR  (Show only errors)
; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
; Development Value: E_ALL
; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
; http://php.net/error-reporting
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT

Notice that error_reporting is actually set to the production value by default, not to the "default" value by default. This is somewhat confusing and is not documented outside of php.ini, so I have not validated this on other distributions.

注意,error_reporting实际上是默认设置为生产值,而不是默认设置为“默认”值。这有点令人困惑,在php之外没有记录。ini,所以我没有在其他发行版中验证这个。

To answer your question, however, this error pops up now when it did not pop up before because:

然而,要回答你的问题,这个错误在以前没有出现时就出现了,因为:

  1. You installed PHP and the new default settings are somewhat poorly documented, but do not exclude E_NOTICE.

    您已经安装了PHP,新的默认设置的文档比较少,但是不排除E_NOTICE。

  2. E_NOTICE warnings like undefined variables and undefined indexes actually help to make your code cleaner and safer. I can tell you that, years ago, keeping E_NOTICE enabled forced me to declare my variables. It made it a LOT easier to learn C, where not declaring variables is much bigger of a nuisance.

    E_NOTICE警告(如未定义的变量和未定义的索引)实际上有助于使代码更简洁、更安全。我可以告诉你,多年前,保持E_NOTICE使我不得不声明我的变量。它使学习C变得容易得多,在这里,不声明变量要大得多。

WHAT CAN I DO ABOUT IT?

  1. Turn off E_NOTICE by copying the "Default value" E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED and replacing it with what is currently uncommented after the equals sign in error_reporting =. Restart Apache, or PHP if using CGI or FPM. Make sure you are editing the "right" php.ini. The correct one will be Apache if you are running PHP with Apache, fpm or php-fpm if running PHP-FPM, cgi if running PHP-CGI, etc. This is not the recommended method, but if you have legacy code that's going to be exceedingly difficult to edit, then it might be your best bet.

    通过复制“默认值”E_ALL & ~E_NOTICE & ~E_STRICT & ~E_STRICT & ~E_DEPRECATED并将其替换为在error_reporting =中等号后当前未注释的内容,从而关闭E_NOTICE。如果使用CGI或FPM,则重新启动Apache或PHP。确保你正在编辑“正确的”ph .ini。正确的将Apache如果您正在运行PHP和Apache,fpm或php-fpm如果php-fpm运行,运行cgi如果PHP-CGI,等等。这是不推荐的方法,但是如果你有遗留代码将会极其困难的编辑,那么它可能是你最好的选择。

  2. Turn off E_NOTICE on the file or folder level. This might be preferable if you have some legacy code but want to do things the "right" way otherwise. To do this, you should consult Apache2, nginx, or whatever your server of choice is. In Apache, you would use php_value inside of <Directory>.

    关闭文件或文件夹级别的E_NOTICE。如果您有一些遗留代码,但是希望以“正确”的方式进行操作,那么这样做可能更好。为此,您应该咨询Apache2、nginx或任何您选择的服务器。在Apache中,您将在 中使用php_value。

  3. Rewrite your code to be cleaner. If you need to do this while moving to a production environment, or don't want someone to see your errors, make sure you are disabling any display of errors, and only logging your errors (see display_errors and log_errors in php.ini and your server settings).

    将代码重写为更简洁。如果在迁移到生产环境时需要这样做,或者不希望有人看到您的错误,请确保禁用了任何错误显示,并且只记录错误(请参见php中的display_errors和log_errors)。ini和您的服务器设置)。

To expand on option 3: This is the ideal. If you can go this route, you should. If you are not going this route initially, consider moving this route eventually by testing your code in a development environment. While you're at it, get rid of ~E_STRICT and ~E_DEPRECATED to see what might go wrong in the future. You're going to see a LOT of unfamiliar errors, but it's going to stop you from having any unpleasant problems when you need to upgrade PHP in the future.

扩展选项3:这是理想的。如果你能走这条路,你应该走。如果您最初不走这条路线,可以考虑在开发环境中测试代码,最终移动这条路线。当您使用它的时候,请去掉~E_STRICT和~E_DEPRECATED,看看将来会出现什么问题。您将会看到许多不熟悉的错误,但是当您将来需要升级PHP时,它将阻止您遇到任何不愉快的问题。

WHAT DO THE ERRORS MEAN?

Undefined variable: my_variable_name - This occurs when a variable has not been defined before use. When the PHP script is executed, it internally just assumes a null value. However, in which scenario would you need to check a variable before it was defined? Ultimately, this is an argument for "sloppy code". As a developer, I can tell you that I love it when I see an open source project where variables are defined as high up in their scopes as they can be defined. It makes it easier to tell what variables are going to pop up in the future, and makes it easier to read/learn the code.

未定义变量:my_variable_name—当变量在使用前没有定义时发生。当执行PHP脚本时,它在内部假设一个空值。但是,在这种情况下,您需要在变量定义之前检查一个变量吗?归根结底,这是“草率代码”的论据。作为一名开发人员,我可以告诉您,当我看到一个开源项目时,我很喜欢它,在这个项目中,变量在它们的作用域中定义得尽可能高。它使我们更容易知道将来会出现什么变量,也使我们更容易阅读/学习代码。

function foo()
{
    $my_variable_name = '';

    //....

    if ($my_variable_name) {
        // perform some logic
    }
}

Undefined index: my_index - This occurs when you try to access a value in an array and it does not exist. To prevent this error, perform a conditional check.

未定义索引:my_index——当您试图访问数组中的值时,它不存在。要防止此错误,请执行条件检查。

// verbose way - generally better
if (isset($my_array['my_index'])) {
    echo "My index value is: " . $my_array['my_index'];
}

// non-verbose ternary example - I use this sometimes for small rules.
$my_index_val = isset($my_array['my_index'])?$my_array['my_index']:'(undefined)';
echo "My index value is: " . $my_index_val;   

Another option is to declare an empty array at the top of your function. This is not always possible.

另一个选项是在函数的顶部声明一个空数组。这不总是可能的。

$my_array = array(
    'my_index' => ''
);

//...

$my_array['my_index'] = 'new string';

(additional tip)

  • When I was encountering these and other issues, I used NetBeans IDE (free) and it gave me a host of warnings and notices. Some of them offer very helpful tips. This is not a requirement, and I don't use IDEs anymore except for large projects. I'm more of a vim person these days :).
  • 当我遇到这些问题和其他问题时,我使用NetBeans IDE(免费),它给了我大量的警告和通知。他们中的一些人提供了非常有用的建议。这不是一个需求,除了大型项目之外,我不再使用ide。现在我更像一个生气勃勃的人。

#16


6  

why not keep things simple?

为什么不把事情简单化呢?

<?php
error_reporting(E_ALL); // making sure all notices are on

function idxVal(&$var, $default = null) {
         return empty($var) ? $var = $default : $var;
  }

echo idxVal($arr['test']);         // returns null without any notice
echo idxVal($arr['hey ho'], 'yo'); // returns yo and assigns it to array index, nice

?>

#17


5  

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);

#18


3  

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:

没有明确的答案,但这里有一些可能的解释,为什么设置可以“突然”改变:

  1. You have upgraded PHP to a newer version which can have other defaults for error_reporting, display_errors or other relevant settings.

    您已经将PHP升级到一个更新的版本,该版本可以有error_reporting、display_errors或其他相关设置的其他默认值。

  2. 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)

    您已经删除或引入了一些代码(可能在依赖项中),在运行时使用ini_set()或error_reporting()来设置相关设置(在代码中搜索这些设置)

  3. You changed the webserver configuration (assuming apache here): .htaccess files and vhost configurations can also manipulate php settings.

    您更改了webserver配置(假设这里是apache): .htaccess文件和vhost配置也可以操作php设置。

  4. 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.

    通常通知不会显示/报告(参见PHP手册),所以在设置服务器时,PHP可能会出现。由于某些原因(文件权限?),ini文件无法被加载,您处于默认设置中。稍后,“bug”被解决(纯属偶然),现在它可以加载正确的php。包含error_reporting设置为显示通知的ini文件。

#19


3  

Another reason why an undefined index notice will be thrown, would be that a column was omitted from a database query.

将抛出未定义索引通知的另一个原因是,在数据库查询中省略了列。

I.e.:

例如:

$query = "SELECT col1 FROM table WHERE col_x = ?";

Then trying to access more columns/rows inside a loop.

然后尝试访问循环中的更多列/行。

I.e.:

例如:

print_r($row['col1']);
print_r($row['col2']); // undefined index thrown

or in a while loop:

或者在一段时间内循环:

while( $row = fetching_function($query) ) {

    echo $row['col1'];
    echo "<br>";
    echo $row['col2']; // undefined index thrown
    echo "<br>";
    echo $row['col3']; // undefined index thrown

}

Something else that needs to be noted is that on a *NIX OS and Mac OS X, things are case-sensitive.

需要注意的是,在*NIX操作系统和Mac OS X上,事物是区分大小写的。

Consult the followning Q&A's on Stack:

请参阅以下堆叠上的问答:

#20


2  

If working with classes you need to make sure you reference member variables using $this:

如果使用类,您需要确保使用$this引用成员变量:

class Person
{
    protected $firstName;
    protected $lastName;

    public function setFullName($first, $last)
    {
        // Correct
        $this->firstName = $first;

        // Incorrect
        $lastName = $last;

        // Incorrect
        $this->$lastName = $last;
    }
}

#21


1  

Probably you were using old PHP version until and now upgraded PHP thats the reason it was working without any error till now from years. until PHP4 there was no error if you are using variable without defining it but as of PHP5 onwards it throws errors for codes like mentioned in question.

可能您一直在使用旧的PHP版本,直到现在才对PHP进行升级,这就是为什么它从几年以来一直没有出现任何错误。在PHP4之前,如果你使用变量而不定义它,就不会出现错误,但是当PHP5以后,它会为问题中提到的代码抛出错误。

#22


1  

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.

在处理文件时,需要适当的封装类型和POST方法,如果表单中没有包含这两个方法,则该方法将触发一个未定义的索引通知。

The manual states the following basic syntax:

手册规定了以下基本语法:

HTML

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

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

参考:

#23


0  

Those notices are because you don't have the used variable defined and my_index key was not present into $my_array variable.

这些注意事项是因为您没有定义使用的变量,my_index键没有出现在$my_array变量中。

Those notices were triggered every time, because your code is not correct, but probably you didn't have the reporting of notices on.

这些通知每次都会被触发,因为您的代码不正确,但是您可能没有通知的报告。

Solve the bugs:

解决错误:

$my_variable_name = "Variable name"; // defining variable
echo "My variable value is: " . $my_variable_name;

if(isset($my_array["my_index"])){
    echo "My index value is: " . $my_array["my_index"]; // check if my_index is set 
}

Another way to get this out:

另一种解决方法是:

ini_set("error_reporting", false)

#24


0  

In PHP you need fist to define the variable after that you can use it.
We can check variable is defined or not in very efficient way!.

在PHP中,需要首先定义变量,然后才能使用它。我们可以用非常有效的方式检查变量是否被定义!

//If you only want to check variable has value and value has true and false value.
//But variable must be defined first.

if($my_variable_name){

}

//If you want to check variable is define or undefine
//Isset() does not check that variable has true or false value
//But it check null value of variable
if(isset($my_variable_name)){

}

Simple Explanation

简单的解释

//It will work with :- true,false,NULL
$defineVarialbe = false;
if($defineVarialbe){
    echo "true";
}else{
    echo "false";
}

//It will check variable is define or not and variable has null value.
if(isset($unDefineVarialbe)){
    echo "true";
}else{
    echo "false";
}