问题:使用PHP的"注意:未定义的变量","注意:未定义的索引"和"注意:未定义的偏移量"

我正在运行PHP脚本,并继续收到类似以下错误:

注意:未定义的变量:第10行的C:\ wamp \ www \ mypath \ index.php中的my_variable_name

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

第10行和第11行看起来像这样:

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

这些错误消息是什么意思?

为什么它们突然出现?我曾经使用此脚本多年,但从未遇到任何问题。

我该如何解决?


这是一个一般参考问题,人们可以重复链接,而不必一遍又一遍地解释问题。我认为这是必要的,因为在此问题上,大多数现实世界的答案都是非常具体的。

相关元讨论:

标签:php,arrays,variables,warnings,undefined-index

Q: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

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

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 is the meaning of these error messages?

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

How do I 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:

回答1:

注意:未定义的变量

PHP手册的广泛见解中:

在将一个文件包含在另一个使用相同变量名的文件中的情况下,依靠未初始化变量的默认值是有问题的。它也是 安全风险。 //www.php.net/manual/zh-CN/ini.core.php#ini.register-globals" rel="noreferrer"> register_globals 已打开。发出 E_NOTICE 级错误在使用未初始化变量的情况下,但是在将元素附加到未初始化数组的情况下则不是。 isset()语言结构可用于检测变量是否已被已经初始化。此外, empty()的解决方案也很理想,因为它不会生成警告或错误消息(如果未初始化变量)。

来自 PHP文档

如果变量不存在,则不会生成警告。这意味着 empty()本质上与!isset($ var)||等效。 $ var == false

这意味着您只能使用empty()来确定是否设置了变量,此外,它还会根据以下0 0.0 """0"false[]

示例:

$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";
});

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

尽管PHP不需要变量声明,但它确实推荐这样做,以避免某些安全性漏洞或bug,因为这些漏洞或bug可能会忘记为变量提供值,该变量将在脚本的后面使用。在未声明变量的情况下,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'] : '';
    

    自PHP 7.0起,它变得更加干净,现在您可以使用空合并运算符

    // Null coalesce operator - No need to explicitly initialize the variable.
    $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. 使用 @运算符抑制该错误。< / p>

注意:强烈建议仅实施第1点。

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

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

解决问题的方法:

  1. 在访问索引之前检查索引是否存在。为此,您可以使用 isset() 或< href=" http://php.net/manual/en/function.array-key-exists.php" rel="noreferrer"> 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变量

在使用$_POST$_GET$_SESSION时,通常会出现上述提示。对于$_POST$_GET,您只需要在使用索引之前检查索引是否存在。对于$_SESSION,您必须确保您的会话以 session_start() 并且该索引也存在。

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

相关:

A1:

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, 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'] ?? '';
    
  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 and are uppercase.

Related:

回答2:

尝试这些

Q1:此通知意味着$ varname不在脚本的当前作用域中定义。

Q2:在使用任何可疑变量之前,使用isset(),empty()条件效果很好。

// recommended solution for recent PHP versions
$user_name = $_SESSION['user_name'] ?? '';

// pre-7 PHP versions
$user_name = '';
if (!empty($_SESSION['user_name'])) {
     $user_name = $_SESSION['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);

有关会话的说明:

A2:

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 for recent PHP versions
$user_name = $_SESSION['user_name'] ?? '';

// pre-7 PHP versions
$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:

回答3:

错误显示 @运算符 < / h3>

对于不想要的和多余的通知,可以使用专用的 @ 运算符来»隐藏«未定义的变量/索引消息。

$var = @($_GET["optional_param"]);
  • 通常不建议这样做。新来者倾向于过度使用它。
  • 这对于应用程序逻辑深处的代码(忽略不应声明的未声明变量)非常不合适,例如功能参数或循环中。
  • isset?:??超级压缩还有一个缺点。通知仍然可以记录。可以使用set_error_handler("var_dump");恢复@隐藏的通知
    • 此外,您不应该习惯于/建议在初始代码中使用if(isset($_POST["shubmit"]))
    • 新来者不会发现这种错别字。在这种情况下,它只会使您失去PHP声明。 验证功能后,仅在内添加@isset
    • 首先解决原因。不是通知。

  • @ 主要适用于$_GET / $_POST输入参数,特别是(如果它们是可选的)

由于这涵盖了大多数此类问题,因此让我们扩展最常见的原因:

$_GET / $_POST / $_REQUEST未定义输入

  • 遇到不确定的索引/偏移量时,您要做的第一件事就是检查拼写错误:
    $count=$_GET["whatnow?"];

    • 这是预期的键名吗,并且出现在每个页面请求中?
    • 变量名称数组索引在PHP中区分大小写。
  • 第二,如果通知没有明显原因,请使用 var_dump < / a>或 print_r 来验证所有输入数组它们的当前内容:

    var_dump($_GET);
    var_dump($_POST);
    //print_r($_REQUEST);
    

    这两个参数都将显示您的脚本是使用正确的权限还是使用任何参数调用的。

  • 或者另外使用您的 浏览器devtools < / strong>( F12 )并检查网络标签中的请求和参数:

    浏览器开发人员工具/网络标签

    POST参数和GET输入将分别显示。

  • 对于$_GET参数,您还可以查看 QUERY_STRING

    print_r($_SERVER);
    

    PHP中有一些规则可以 coalesce 非标准参数名称添加到超全局变量中。 Apache可能也会做一些重写。您还可以通过这种方式查看提供的原始$_COOKIES和其他HTTP请求标头。

  • 显然,您可以在浏览器地址栏中查看获取参数

    http://example.org/script.php?id=5&sort=desc

    name=value<?问号后面的/ code>对是您的查询(GET)参数。因此,此URL仅可能产生$_GET["id"]$_GET["sort"]

  • 最后,如果需要一个参数但什么都没有收到,请检查您的

    声明。
  • >
    • 确保每个必需的输入都有一个
    • id=title=属性不足。
    • 应使用method=POST表单填充$_POST
    • method=GET(或忽略它)将产生$_GET变量。
    • 表单还可以通过$ _GET和$ _POST中的其余method=POST字段一起提供action=script.php?get=param。< / li>
    • 使用现代PHP配置(≥5.6),它已经可行(不流行)再次使用 $_REQUEST['vars'] GET和POST参数。
  • 如果您使用的是mod_rewrite,则应同时检查access.log并启用 RewriteLog 找出不存在的参数。

$_FILES

  • 相同的健全性检查适用于文件上传和$_FILES["formname"]
  • 此外还要检查enctype=multipart/form-data
  • 以及声明中的method=POST
  • 另请参阅: PHP未定义索引错误$ _FILES?

$_COOKIE

  • $_COOKIE数组永远不会在setcookie()之后立即填充,而只会在任何后续HTTP请求中填充。
  • 此外,它们的有效性超时,它们可能会受到子域或单个路径的限制,用户和浏览器只能拒绝或删除它们。

A3:

Error display @ operator

For undesired and redundant notices, one could use the dedicated @ operator to »hide« undefined variable/index messages.

$var = @($_GET["optional_param"]);
  • This is usually discouraged. Newcomers tend to way overuse it.
  • It's very inappropriate for code deep within the application logic (ignoring undeclared variables where you shouldn't), e.g. for function parameters, or in loops.
  • There's one upside over the isset?: or ?? super-supression however. Notices still can get logged. And one may resurrect @-hidden notices with: set_error_handler("var_dump");
    • Additonally you shouldn't habitually use/recommend if (isset($_POST["shubmit"])) in your initial code.
    • Newcomers won't spot such typos. It just deprives you of PHPs Notices for those very cases. Add @ or isset only after verifying functionality.
    • Fix the cause first. Not the notices.

  • @ is mainly acceptable for $_GET/$_POST input parameters, specifically if they're optional.

And since this covers the majority of such questions, let's expand on the most common causes:

$_GET / $_POST / $_REQUEST undefined input

  • First thing you do when encountering an undefined index/offset, is check for typos:
    $count = $_GET["whatnow?"];

    • Is this an expected key name and present on each page request?
    • Variable names and array indicies are case-sensitive in PHP.
  • Secondly, if the notice doesn't have an obvious cause, use var_dump or print_r to verify all input arrays for their curent content:

    var_dump($_GET);
    var_dump($_POST);
    //print_r($_REQUEST);
    

    Both will reveal if your script was invoked with the right or any parameters at all.

  • Alternativey or additionally use your browser devtools (F12) and inspect the network tab for requests and parameters:

    POST parameters and GET input will be be shown separately.

  • For $_GET parameters you can also peek at the QUERY_STRING in

    print_r($_SERVER);
    

    PHP has some rules to coalesce non-standard parameter names into the superglobals. Apache might do some rewriting as well. You can also look at supplied raw $_COOKIES and other HTTP request headers that way.

  • More obviously look at your browser address bar for GET parameters:

    http://example.org/script.php?id=5&sort=desc

    The name=value pairs after the ? question mark are your query (GET) parameters. Thus this URL could only possibly yield $_GET["id"] and $_GET["sort"].

  • Finally check your <form> and <input> declarations, if you expect a parameter but receive none.

    • Ensure each required input has an <input name=FOO>
    • The id= or title= attribute does not suffice.
    • A method=POST form ought to populate $_POST.
    • Whereas a method=GET (or leaving it out) would yield $_GET variables.
    • It's also possible for a form to supply action=script.php?get=param via $_GET and the remaining method=POST fields in $_POST alongside.
    • With modern PHP configurations (≥ 5.6) it has become feasible (not fashionable) to use $_REQUEST['vars'] again, which mashes GET and POST params.
  • If you are employing mod_rewrite, then you should check both the access.log as well as enable the RewriteLog to figure out absent parameters.

$_FILES

  • The same sanity checks apply to file uploads and $_FILES["formname"].
  • Moreover check for enctype=multipart/form-data
  • As well as method=POST in your <form> declaration.
  • See also: PHP Undefined index error $_FILES?

$_COOKIE

  • The $_COOKIE array is never populated right after setcookie(), but only on any followup HTTP request.
  • Additionally their validity times out, they could be constraint to subdomains or individual paths, and user and browser can just reject or delete them.

回答4:

通常是因为"编程错误",以及现在或以后发生错误的可能性。

  1. 如果输入有误,请首先对变量进行适当的赋值:$ varname = 0;
  2. 如果确实只是有时定义了它,请对其进行测试:if(isset($varname)),然后再使用它
  3. 如果是因为您拼写错误,只需更正
  4. 甚至可能在您 PHP设置
  5. 中打开警告

A4:

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. If it really is only defined sometimes, test for it: if (isset($varname)), before using it
  3. If it's because you spelled it wrong, just correct that
  4. Maybe even turn of the warnings in you PHP-settings

回答5:

这意味着您正在测试,评估或打印尚未分配任何内容的变量。这意味着您有错别字,或者您需要先检查变量是否已初始化为某些东西。检查您的逻辑路径,可以在一个路径中设置它,而不能在另一个路径中设置。

A5:

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.

回答6:

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

我的解决方案是此功能:

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

因此,如果我要引用$ name并回显(如果存在),我只需写:

<?=ifexists('name')?>

对于数组元素:

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

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

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

A6:

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:

<?=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']:

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

回答7:

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

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

这种单线几乎等同于:

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

如果您绝对想要 string 值,就像:

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

A7:

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:

这是因为未定义变量'$ user_location'。如果要在其中声明" $ user_location"变量的情况下使用if循环,则还必须具有else循环并对其进行定义。例如:

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

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

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

A8:

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:

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

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

回答9:

回复"",为什么它们突然出现?我曾经使用此脚本多年,但从未遇到任何问题。"

对于大多数站点,在"显示所有错误,但不显示"通知"和"已弃用""的"默认"错误报告下运行是非常普遍的。这将在php.ini中设置,并应用于服务器上的所有站点。这意味着示例中使用的"通知"将被隐藏(隐藏),而其他更重要的错误将被显示/记录。

另一个关键设置是可以隐藏错误(即display_errors设置为" off"或" syslog")。

在这种情况下,将发生以下情况:要么将error_reporting更改为还显示通知(根据示例),并且/或者将设置更改为display_errors在屏幕上显示(而不是禁止显示/记录它们)。

为什么要更改?

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

不过,也可以在以下位置覆盖这些设置

  • .htconf(网络服务器配置,包括虚拟主机和子配置)*
  • .htaccess
  • 使用php代码本身

,其中任何一个都可能已更改。

Web服务器配置还可以启用/禁用.htaccess指令,这还增加了复杂性,因此,如果您在.htaccess中有突然启动/停止工作的指令,则需要进行检查。

(。htconf / .htaccess假定您正在以apache身份运行。如果运行命令行,则不适用;如果运行IIS或其他网络服务器,则需要相应地检查那些配置)

摘要

    php.ini中的
  • 检查error_reportingdisplay_errors php指令未更改,或者您没有使用与以前不同的php.ini。
  • .htconf(或虚拟主机等)中的error_reportingdisplay_errors php指令未更改
  • .htaccess中的
  • 检查error_reportingdisplay_errors php指令未更改
  • 如果您在.htaccess中有指令,请检查.htconf文件中是否仍允许使用这些指令
  • 最后检查您的代码;可能是无关的库;查看是否在此处设置了error_reportingdisplay_errors php指令。

A9:

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.

The other critical setting is the errors can be hidden (i.e. display_errors set to "off" or "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).

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.

However it is also possible to override these settings in

  • .htconf (webserver configuration, including vhosts and sub-configurations)*
  • .htaccess
  • in php code itself

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.

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

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.
  • Check error_reporting and display_errors php directives in .htconf (or vhosts etc) have not changed
  • Check error_reporting and display_errors php directives in .htaccess have not changed
  • If you have directive in .htaccess, check if they are still permitted in the .htconf file
  • Finally check your code; possibly an unrelated library; to see if error_reporting and display_errors php directives have been set there.

回答10:

快速解决方案是在代码顶部将变量分配为null

$user_location = null;

A10:

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

$user_location = null;

回答11:

我曾经诅咒这个错误,但是提醒您逃避用户输入可能会有所帮助。

例如,如果您认为这很聪明,则为简写代码:

// Echo whatever the hell this is
<?=$_POST['something']?>

...再想一想!更好的解决方案是:

// If this is set, echo a filtered version
<?=isset($_POST['something']) ? html($_POST['something']) : ''?>

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

A11:

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)

回答12:

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

echo "My index value is: " . ($my_array["my_index"] ?? '');

等于:

echo "My index value is: " . (isset($my_array["my_index"]) ? $my_array["my_index"] : '');

PHP手册PHP 7.0

A12:

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

回答13:

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

您的代码将为-

$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;
}

A13:

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

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

回答14:

使用非常简单的语言
错误是您使用的变量$user_location先前没有定义,并且没有任何变量值,因此,我建议您声明此变量之前 使用,例如:


$user_location='';

$user_location='LosAngles';
这是您可能会遇到的非常常见的错误。因此,不必担心,只需声明变量并享受编码

A14:

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 = '';
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.

回答15:

为什么不保持简单?

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

?>

A15:

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

?>

回答16:

为什么会这样?

随着时间的流逝,PHP已成为一种更加注重安全性的语言。以前默认情况下已关闭的设置现在默认情况下已打开。一个完美的例子是E_STRICT,默认情况下,该代码在 PHP 5.4.0

此外,根据PHP文档,默认情况下,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

请注意,默认情况下,error_reporting实际上设置为生产值,而不是默认设置为"默认"值。这有些令人困惑,并且没有在php.ini之外进行记录,因此我 not 在其他发行版中对此进行了验证。

但是,为回答您的问题,此错误以前未弹出时会立即弹出,原因是:

  1. 您已安装PHP,并且新的默认设置在某些情况下没有得到很好的记录,但不排除E_NOTICE

  2. 未定义的变量和未定义的索引之类的
  3. E_NOTICE警告实际上有助于使代码更干净,更安全。我可以告诉你,几年前,保持启用E_NOTICE的行为迫使我声明变量。它使很多人更容易学习C语言,而不是声明变量带来的麻烦更大。

我该怎么办?

  1. 通过复制"默认值" E_ALL&〜E_NOTICE&〜E_STRICT&〜E_DEPRECATED来关闭E_NOTICE,然后将其替换为当前未注释的内容等于登录error_reporting=。重新启动Apache,如果使用CGI或FPM,则重新启动PHP。确保您正在编辑"正确的" php.ini。如果您将PHP与Apache一起运行,则正确的将是Apache,如果运行PHP-FPM,则将fpm或php-fpm,如果运行PHP-CGI,则将cgi,等等。这不是推荐的方法,但是如果您拥有将要使用的遗留代码,很难编辑,那可能是最好的选择。

  2. 在文件或文件夹级别上关闭E_NOTICE。如果您有一些旧代码,但又想以"正确"的方式进行操作,则这可能是更可取的。为此,您应该查阅Apache2,Nginx或您选择的任何服务器。在Apache中,应在 内使用php_value

  3. 重写代码以使代码更整洁。如果您在移至生产环境时需要执行此操作,或者不想让别人看到您的错误,请确保禁用任何错误显示,并且仅记录您的错误(请参见php.ini中的display_errors log_errors和您的服务器设置)。

要扩展选项3:这是理想的选择。如果可以走这条路,那应该。如果您最初不打算走这条路线,请考虑通过在开发环境中测试代码来最终走这条路线。在使用它时,请摆脱〜E_STRICT〜E_DEPRECATED,以查看将来可能出什么问题。您将看到很多不熟悉的错误,但是当将来需要升级PHP时,它将阻止您遇到任何不愉快的问题。

错误意味着什么?

未定义变量:my_variable_name-当在使用前尚未定义变量时,会发生这种情况。当执行PHP脚本时,它在内部仅假定为空值。但是,在哪种情况下您需要在定义变量之前检查变量?最终,这是"草率代码"的参数。作为开发人员,当我看到一个开源项目,其中变量在其作用域中被定义为较高时,我可以告诉您我喜欢它。这样可以更轻松地告诉您将来会弹出哪些变量,并且可以更轻松地读取/学习代码。

function foo()
{
    $my_variable_name = '';

    //....

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

未定义索引: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;   

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

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

//...

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

(其他提示)

  • 遇到这些问题和其他问题时,我使用了 NetBeans IDE (免费),它为我提供了一个主机警告和注意事项。其中一些提供了非常有用的提示。这不是必需的,除了大型项目之外,我不再使用IDE。这些天我更像一个vim的人了:)。

A16:

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.

Furthermore, according to PHP documentation, by default, 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.

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

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.

  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, were not declaring variables is much bigger of a nuisance.

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.

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

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

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.

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.

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.

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

回答17:

未定义索引表示在您请求的数组中不可用的数组索引,例如

<?php 

$newArray[] = {1,2,3,4,5};
print_r($newArray[5]);

?>

未定义变量表示您完全使用了不存在的变量,或者未使用该名称定义或初始化的变量,例如

<?php print_r($myvar); ?>

未定义的偏移量意味着您在数组中请求了不存在的键。解决方案是使用前检查

php> echo array_key_exists(1, $myarray);

A17:

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:

关于这部分问题:

为什么它们突然出现?我曾经使用此脚本多年,但从未遇到任何问题。

没有确切的答案,但以下是一些可能导致设置"突然"更改的可能解释:

  1. 您已将PHP升级到了较新的版本,该版本可以具有error_reporting,display_errors或其他相关设置的其他默认值。

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

  3. 您更改了Web服务器配置(此处为apache):.htaccess文件和虚拟主机配置也可以操纵php设置。

  4. 通常不会显示/报告通知(请参见 PHP手册),则有可能在设置服务器时,由于某种原因(文件权限?)而无法加载php.ini文件,并且您使用的是默认设置。后来,"错误"得到了解决(偶然),现在它可以加载error_reporting设置为显示通知的正确的php.ini文件。

A18:

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.

  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)

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

  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.

回答19:

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

class Person
{
    protected $firstName;
    protected $lastName;

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

        // Incorrect
        $lastName = $last;

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

A19:

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

class Person
{
    protected $firstName;
    protected $lastName;

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

        // Incorrect
        $lastName = $last;

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

回答20:

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

即:

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

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

即:

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

while循环中:

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

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

}

还有一点需要注意的是,在* NIX OS和Mac OS X上,情况区分大小写。

请咨询以下问答集:

A20:

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.

Consult the followning Q&A's on Stack:

回答21:

使用三元简单,可读且干净:

Pre PHP 7
如果已设置,则将变量分配给另一个变量的值,否则分配null(或其他< em>默认您需要的值):

$newVariable = isset($thePotentialData) ? $thePotentialData : null;

PHP 7 +
除了使用空合并运算符。内置时不再需要调用isset(),并且无需提供要返回的变量,因为它假定返回要检查的变量的值:

$newVariable = $thePotentialData ?? null;

两者都将停止OP问题中的通知,并且两者均与以下内容完全相同:

if (isset($thePotentialData)) {
    $newVariable = $thePotentialData;
} else {
    $newVariable = null;
}


如果您不需要设置新变量,则可以直接使用三元组的返回值,例如echo,函数参数等:

回声:

echo 'Your name is: ' . isset($name) ? $name : 'You did not provide one';

功能:

$foreName = getForeName(isset($userId) ? $userId : null);

function getForeName($userId)
{
    if ($userId === null) {
        // Etc
    }
}

上面的方法与数组(包括会话等)相同,将要检查的变量替换为例如:
$_SESSION['checkMe']
您需要,例如:
$clients['personal']['address']['postcode']


抑制:

可以使用@抑制PHP通知或降低错误报告级别,但是不能解决问题,只是停止了在报告中报告该问题。错误日志。这意味着您的代码仍尝试使用未设置的变量,这可能会或可能不会意味着某些事情无法按预期工作,具体取决于缺失值的重要性。

您确实应该检查此问题并进行适当处理,或者发送不同的消息,甚至为其他所有内容返回空值以标识准确的状态。

如果您只关心通知不在错误日志中,那么可以选择忽略错误日志。

A21:

Using a ternary is simple, readable, and clean:

Pre PHP 7
Assign a variable to the value of another variable if it's set, else assign null (or whatever default value you need):

$newVariable = isset($thePotentialData) ? $thePotentialData : null;

PHP 7+
The same except using Null Coalescing Operator. There's no longer a need to call isset() as this is built in, and no need to provide the variable to return as it's assumed to return the value of the variable being checked:

$newVariable = $thePotentialData ?? null;

Both will stop the Notices from the OP question, and both are the exact equivalent of:

if (isset($thePotentialData)) {
    $newVariable = $thePotentialData;
} else {
    $newVariable = null;
}


If you don't require setting a new variable then you can directly use the ternary's returned value, such as with echo, function arguments, etc:

Echo:

echo 'Your name is: ' . isset($name) ? $name : 'You did not provide one';

Function:

$foreName = getForeName(isset($userId) ? $userId : null);

function getForeName($userId)
{
    if ($userId === null) {
        // Etc
    }
}

The above will work just the same with arrays, including sessions etc, replacing the variable being checked with e.g.:
$_SESSION['checkMe']
or however many levels deep you need, e.g.:
$clients['personal']['address']['postcode']


Suppression:

It is possible to suppress the PHP Notices with @ or reduce your error reporting level, but it does not fix the problem, it simply stops it being reported in the error log. This means that your code still tried to use a variable that was not set, which may or may not mean something doesn't work as intended - depending on how crucial the missing value is.

You should really be checking for this issue and handling it appropriately, either serving a different message, or even just returning a null value for everything else to identify the precise state.

If you just care about the Notice not being in the error log, then as an option you could simply ignore the error log.

回答22:

提交HTML表单后,变量不存在的常见原因是

标记中不包含form元素:

示例:

中未包含的元素
<form action="example.php" method="post">
    <p>
        <input type="text" name="name" />
        <input type="submit" value="Submit" />
    </p>
</form>

<select name="choice">
    <option value="choice1">choice 1</option>
    <option value="choice2">choice 2</option>
    <option value="choice3">choice 3</option>
    <option value="choice4">choice 4</option>
</select>

示例:元素现在包含在

<form action="example.php" method="post">
    <select name="choice">
        <option value="choice1">choice 1</option>
        <option value="choice2">choice 2</option>
        <option value="choice3">choice 3</option>
        <option value="choice4">choice 4</option>
    </select>
    <p>
        <input type="text" name="name" />
        <input type="submit" value="Submit" />
    </p>
</form>

A22:

One common cause of a variable not existing after an HTML form has been submitted is the form element is not contained within a <form> tag:

Example: Element not contained within the <form>

<form action="example.php" method="post">
    <p>
        <input type="text" name="name" />
        <input type="submit" value="Submit" />
    </p>
</form>

<select name="choice">
    <option value="choice1">choice 1</option>
    <option value="choice2">choice 2</option>
    <option value="choice3">choice 3</option>
    <option value="choice4">choice 4</option>
</select>

Example: Element now contained within the <form>

<form action="example.php" method="post">
    <select name="choice">
        <option value="choice1">choice 1</option>
        <option value="choice2">choice 2</option>
        <option value="choice3">choice 3</option>
        <option value="choice4">choice 4</option>
    </select>
    <p>
        <input type="text" name="name" />
        <input type="submit" value="Submit" />
    </p>
</form>

回答23:

可能直到现在您都在使用旧版本的PHP,现在又升级了PHP,这就是多年来它一直运行无误的原因。直到PHP4为止,如果您使用的是未定义变量就没有错误,但是从PHP5开始,它会为上述代码引发错误。

A23:

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.

回答24:

处理文件时,需要适当的enctype和POST方法,如果表单中未包含任何两者,则会触发未定义的索引通知。

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

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

?>

参考:

A24:

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:

回答25:

我问了一个有关此问题的信息,并给我发了以下帖子:

这个问题已经在这里有了答案

使用PHP的"通知:未定义变量","通知:未定义索引"和"通知:未定义偏移量"

我在这里分享我的问题和解决方案:

这是错误:

在此处输入图片描述

第154行是问题所在。这就是我在154行中的内容:

153    foreach($cities as $key => $city){
154        if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){

我认为问题是我正在写变量$city的条件,该条件不是键,而是$key=>$city中的值。首先,您可以确认是否是警告的原因?其次,如果这是问题所在,为什么我不能基于该值编写条件?

必须写我写条件的键吗?

更新1:问题是执行$citiesCounterArray[$key]时,有时$key对应于中不存在的键$ citiesCounterArray 数组,但是根据我的循环数据并不总是这样。我需要设置一个条件,以便如果$key存在于数组中,然后运行代码,否则,跳过它。

更新2:这就是我通过使用array_key_exists()修复它的方式:

foreach($cities as $key => $city){
    if(array_key_exists($key, $citiesCounterArray)){
        if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){

A25:

I asked a question about this and I was referred to this post with the message:

This question already has an answer here:

“Notice: Undefined variable”, “Notice: Undefined index”, and “Notice: Undefined offset” using PHP

I am sharing my question and solution here:

This is the error:

Line 154 is the problem. This is what I have in line 154:

153    foreach($cities as $key => $city){
154        if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){

I think the problem is that I am writing if conditions for the variable $city, which is not the key but the value in $key => $city. First, could you confirm if that is the cause of the warning? Second, if that is the problem, why is it that I cannot write a condition based on the value? Does it have to be with the key that I need to write the condition?

UPDATE 1: The problem is that when executing $citiesCounterArray[$key], sometimes the $key corresponds to a key that does not exist in the $citiesCounterArray array, but that is not always the case based on the data of my loop. What I need is to set a condition so that if $key exists in the array, then run the code, otherwise, skip it.

UPDATE 2: This is how I fixed it by using array_key_exists():

foreach($cities as $key => $city){
    if(array_key_exists($key, $citiesCounterArray)){
        if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){

回答26:

每当我们使用未设置的变量时,就会发生这些错误。

处理这些问题的最佳方法是在开发过程中设置错误报告。

要在以下位置设置错误报告:

ini_set('error_reporting', 'on');
ini_set('display_errors', 'on');
error_reporting(E_ALL);

在生产服务器上,错误报告处于关闭状态,因此,我们不会收到这些错误。

但是,在开发服务器上,我们可以将错误报告设置为打开。

要摆脱此错误,我们看下面的示例:

if ($my == 9) {
 $test = 'yes';  // Will produce error as $my is not 9.
}
echo $test;

我们可以在分配变量值或使用它们之前将变量初始化为NULL

因此,我们可以将代码修改为:

$test = NULL;
if ($my == 9) {
 $test = 'yes';  // Will produce error as $my is not 9.
}
echo $test;

这不会打扰任何程序逻辑,并且即使$test没有值,也不会产生通知。

因此,基本上,将错误报告设置为开发始终会更好。

并修复所有错误。

在生产中,错误报告应设置为关闭。

A26:

These errors occur whenever we are using a variable that is not set.

The best way to deal with these is set error reporting on while development.

To set error reporting on:

ini_set('error_reporting', 'on');
ini_set('display_errors', 'on');
error_reporting(E_ALL);

On production servers, error reporting is off, therefore, we do not get these errors.

On the development server, however, we can set error reporting on.

To get rid of this error, we see the following example:

if ($my == 9) {
 $test = 'yes';  // Will produce error as $my is not 9.
}
echo $test;

We can initialize the variables to NULL before assigning their values or using them.

So, we can modify the code as:

$test = NULL;
if ($my == 9) {
 $test = 'yes';  // Will produce error as $my is not 9.
}
echo $test;

This will not disturb any program logic and will not produce Notice even if $test does not have value.

So, basically, its always better to set error reporting ON for development.

And fix all the errors.

And on production, error reporting should be set to off.

回答27:

这些注意是因为您没有所使用的变量definedmy_index键不存在于$my_array变量中。

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

解决错误:

$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 
}

另一种解决方法:

ini_set("error_reporting", false)

A27:

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

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)

回答28:

在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)){

}

简单说明

//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";
}

A28:

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

//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";
}
回到顶部