“注意:未定义的变量”:“注意:未定义的索引”警告:未定义的数组键&quot&quitd&quitd:&quote&quits;使用PHP
我正在运行一个PHP脚本,并继续收到以下错误:
注意:c:\ wamp \ www \ mypath \ mypath \ index.php in Line 10
注意:未定义的索引:my_index c:\ wamp \ www \ mypath \ mypath \ index.php在第11行
上警告:c:\ wamp \ www \ mypath \ mypath \ index.php in Line 11
行10和11看起来像这样:
echo "My variable value is: " . $my_variable_name;
echo "My index value is: " . $my_array["my_index"];
这些错误消息的含义是什么?
为什么它们突然出现?我曾经使用这个脚本多年了,我从来没有任何问题。
我该如何修复它们?
这是一个一般参考问题供人们链接为重复,而不必一遍又一遍地解释问题。我觉得这是必要的,因为这个问题上的大多数现实世界答案都是非常具体的。
相关的元讨论:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(29)
在非常简单的语言中:
错误是您使用的是变量
$ user_location
,该> the> n n's by''''''''''''''''''''''''''''''''''''''''''''''''''''''>> location >因此,我建议您在 使用之前取悦此变量。例如:$user_location = '';
Or
$user_location = 'Los Angles';
这是您可能面临的非常常见的错误。所以不用担心;只需声明变量,享受编码即可。
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.
保持简单:
Keep things simple:
未定义的索引意味着您要求使用不可用的数组索引的数组中。例如,
未定义的变量意味着您完全使用了现有变量,或者未通过该名称定义或初始化的变量。例如,
未定义的偏移意味着在您要求使用不存在的键的数组中。解决方案是在使用前检查:
An undefined index means in an array you requested for an unavailable array index. For example,
An undefined variable means you have used completely not an existing variable or which is not defined or initialized by that name. For example,
An undefined offset means in an array you have asked for a nonexisting key. And the solution for this is to check before use:
关于这个问题的这一部分:
没有明确的答案,但这里有一些可能的解释,即设置为什么可以“突然”更改:
您已将PHP升级到较新版本,该版本可以具有其他默认值forror_reporting,display_errors或其他相关设置。
您已删除或介绍了一些代码(可能是在依赖项中),该代码在运行时使用
ini_set()
或 error_reporting()(在代码)您更改了Web服务器配置(在此处假设Apache):
.htaccess
文件和VHOST配置也可以操纵PHP设置。通常不会显示/报告显示(请参阅 php手册)
因此,在设置服务器时,由于某种原因无法加载PHP.Ini文件(文件权限??),并且您在默认设置上。后来,(偶然地)解决了“错误”,现在它可以加载正确的php.ini文件,其中包括error_reporting设置以显示通知。< / p>
Regarding this part of the question:
No definite answers but here are a some possible explanations of why settings can 'suddenly' change:
You have upgraded PHP to a newer version which can have other defaults for error_reporting, display_errors or other relevant settings.
You have removed or introduced some code (possibly in a dependency) that sets relevant settings at runtime using
ini_set()
orerror_reporting()
(search for these in the code)You changed the webserver configuration (assuming apache here):
.htaccess
files and vhost configurations can also manipulate php settings.Usually notices don't get displayed / reported (see PHP manual)
so it is possible that when setting up the server, the php.ini file could not be loaded for some reason (file permissions??) and you were on the default settings. Later on, the 'bug' has been solved (by accident) and now it CAN load the correct php.ini file with the error_reporting set to show notices.
使用 ternary oterator ,可读和清洁:
pre php 7
如果设置为另一个变量的值您需要的值):
php 7+
相同,除了使用无效的合并操作员。不再需要在内置的情况下调用
isset()
,也不需要提供变量以返回的变量,因为假定要返回被检查的变量的值:都/strong>将在OP的问题中停止通知,并且 act ot 的确切等同是:
如果您不需要设置新变量,则可以直接使用三元运算符的返回值,例如
echo
,函数参数等:echo:echo:
函数:
以上将与数组(包括会话等)相同,替换了用EG替换的变量:
$ _ session ['checkme']
您需要的许多级别,例如:
$ client
或 :
可以用
@
抑制PHP通知,或降低您的错误报告级别,但无法解决问题。它只是停止在错误日志中报告它。这意味着您的代码仍在尝试使用未设置的变量,这可能意味着也可能不会按预期工作,这取决于丢失值的重要性。您应该真正检查此问题并适当地处理它,要么提供不同的消息,甚至只是返回其他所有内容以识别精确状态。
如果您只是关心通知不在错误日志中,则作为选项,您可以简单地忽略错误日志。
Using a ternary operator 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):PHP 7+
The same except using the 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:Both will stop the Notices from the OP's question, and both are the exact equivalent of:
If you don't require setting a new variable then you can directly use the ternary operator's returned value, such as with
echo
, function arguments, etc.:Echo:
Function:
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.
如果使用类,则需要确保使用
$ this
的参考成员变量:If working with classes you need to make sure you reference member variables using
$this
:不确定的索引通知将被抛出的另一个原因是,数据库查询中省略了列。
IE:
然后尝试在循环中访问更多的列/行。
即:
或在循环中:
需要注意的是 *nix OS和Mac OS X上的其他内容,情况对病例敏感。
请咨询堆栈上的引物Q&amp; a是:
是mysql情况中的表名敏感
mysql- MySQL-不同服务器中的案例敏感问题
Another reason why an undefined index notice will be thrown, would be that a column was omitted from a database query.
I.e.:
Then trying to access more columns/rows inside a loop.
I.e.:
or in a
while
loop: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:
Are table names in MySQL case sensitive?
mysql case sensitive table names in queries
MySql - Case Sensitive issue of tables in different server
提交 html 表格之后,不存在的变量的一个常见原因是
&lt; form&gt;
tag:示例:element: element:element:element:element:element:element:element:element:不包含在
&lt; form&gt;
示例中:element现在包含在
&lt; form&gt;
中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>
Example: Element now contained within the
<form>
每当我们使用未设置的变量时,就会发生这些错误。
处理这些问题的最佳方法是开发期间的设置错误报告。
要设置错误报告:
在生产服务器上,错误报告已关闭,因此,我们没有收到这些错误。
但是,在开发服务器上,我们可以设置错误报告。
为了摆脱此错误,我们看到以下示例:
在分配其值或使用它们之前,我们可以将变量初始化为
null
。因此,我们可以将代码修改为:
这不会打扰任何程序逻辑,即使
$ test
没有值,也不会产生通知。因此,基本上,最好设置错误报告开发的错误。
并修复所有错误。
并且在生产中,应将错误报告设置为关闭。
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:
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:
We can initialize the variables to
NULL
before assigning their values or using them.So, we can modify the code as:
This will not disturb any program logic and will not produce a Notice even if
$test
does not have a value.So, basically, it’s always better to set error reporting ON for development.
And fix all the errors.
And on production, error reporting should be set to off.
我问了一个问题,并将其转介给了这篇文章:
我在这里分享我的问题和解决方案:
这是错误:
第154行是问题所在。这是我在第154行中的内容:
我认为问题是我正在编写是否为变量
$ city
的条件,这不是关键,而是$ key =&gt中的值; $ City
。首先,您能确认这是警告的原因吗?其次,如果那是问题,为什么我不能基于值编写条件?是否必须与我需要编写条件的钥匙?更新1:问题是,当执行
$ cotityCountraray [$ key]
时,有时$ key
对应于$ $ citiesCountarRay中不存在的键< /code>数组,但基于我的循环数据并非总是如此。我需要设置条件,以便如果
$ key
存在数组中,则运行代码,否则请跳过它。更新2:这是我使用
array_key_exists()
:I asked a question about this and I was referred to this post with the message:
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:
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()
:可能您一直在使用旧的PHP版本,直到现在升级为PHP,这是它运行起来的原因,直到几年来一直没有任何错误。
在PHP 4之前,如果您使用变量而不定义该变量,则没有错误,但是从PHP&nbsp; 5开始,它会为所提到的代码丢弃错误。
Probably you were using an old PHP version until and now upgraded PHP that’s the reason it was working without any error till now from years.
Until PHP 4 there was no error if you are using variable without defining it but as of PHP 5 onwards it throws errors for codes like mentioned in question.
如果要将数据发送到API,只需使用 isset() :
如果是由于会话是错误的,请确保您已经正确启动了会话。
If you are sending data to an API, simply use isset():
If it is an error is because of a session, make sure you have started the session properly.
这些通知是因为您没有使用过的变量
定义
和my_index
键没有在$ my_array
变量中存在。这些通知每次都会触发,因为您的
代码
不正确,但是您可能没有报告通知的报告。解决错误:
解决此问题的另一种方法:
Those notices are because you don't have the used variable
defined
andmy_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:
Another way to get this out:
在处理文件时,需要使用适当的副类型和邮政方法,如果未包含在表单中,这将触发未定义的索引通知。
该手册列出以下基本语法:
html
php
参考:
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
PHP
Reference:
在PHP中,您首先需要定义变量。之后,您可以使用它。
我们可以检查变量是否以非常有效的方式定义!
简单的解释
In PHP you need first to define the variable. After that you can use it.
We can check if a variable is defined or not in a very efficient way!
Simple Explanation
此错误消息是指在访问不存在的变量(或数组元素)时发现错别字或错误的PHP程序员。因此,一个好的程序员:
注意 /警告:未定义的变量
,尽管PHP不需要变量声明,但它确实建议它,以避免某些安全漏洞或错误,在这些漏洞或错误中,人们忘记将值给出一个可变量的值,该变量将在以后在脚本中使用。在未确定变量的情况下,PHP的作用是
e_warning
级别的错误。该警告可帮助程序员发现拼写错误的变量名称或类似的错误(例如,将变量分配给评估为false的条件的内部值)。此外,还有其他可能的问题具有非初始化的变量。因为它是在PHP手册中,
这意味着变量可以从随附的文件中获取一个值,并且将使用此值代替
null
,人们期望访问非启用变量,这可能会导致无法预测的结果。为了避免这种情况,最好在使用前初始化PHP文件中的所有变量。处理问题的方法:
推荐:在使用前声明每个变量。这样,只有当您实际犯错,尝试使用不存在的变量时,您才会看到此错误 - 此错误消息存在。
定义变量但在函数中不可见的特殊情况。 PHP中的功能具有自己的 variable范围,如果您需要在函数中使用一个来自外部的变量,其值必须作为函数参数传递:
抑制NULL合并运算符的误差。但是请记住,这种方式PHP将无法通知您有关使用错误的变量名称的通知。
对于古代PHP版本(&lt; 7.0)带有三元的Isset()可以使用
请注意,尽管这只是一个特定的错误,但它本质上仍然是一个错误抑制。因此,它可能会通过标记单位化变量来阻止PHP帮助您。
用@ operator 来抑制错误。出于历史原因而留在这里,但确实不应该发生。
注意:< / strong>强烈建议实现点1。
注意:未定义的索引 /未定义的偏移 /警告:未定义的数组键,
当您(或PHP)尝试访问一个不确定的索引时,会出现此通知 /警告大批。
内部数组
在处理内部数组时(在您的代码中定义的内部数组)时,态度应完全相同:只需在使用前初始化所有键即可。这样,此错误将执行其预期工作:通知程序员有关其代码中的错误。因此方法是相同的:
推荐:声明您的数组元素:
特殊情况是某些函数返回数组或其他值时,例如
null
或> false
。然后必须在尝试访问数组元素之前对其进行测试,例如带有外部数组的外部数组
(例如
$ _ post < / code> /
$ _ get < / code> / code> /
$ _ sessign < /code>或json输入)情况有些不同,因为程序员对此类数组的内容没有控制权。因此,可以证明检查某些密钥存在,甚至分配缺少密钥的默认值。
当PHP脚本包含HTML表单时,自然而然的是,在第一个载荷上没有形式内容。因此,这样的脚本应检查是否提交表格
某些HTML表单元素(例如复选框)如果未检查,则不会将其发送到服务器。在这种情况下
但分配应在脚本的最初完成。 验证所有输入,将其分配给本地变量,然后在代码中一直使用它们。因此,您将要访问的每个变量都会故意存在。
相关:
This error message is meant to help a PHP programmer to spot a typo or a mistake when accessing a variable (or an array element) that doesn't exist. So a good programmer:
Notice / Warning: Undefined variable
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 an error of
E_WARNING
level.This warning helps a programmer to spot a misspelled variable name or a similar kind of mistake (like a variable was assigned a value inside of a condition that evaluated to false). Besides, there are other possible issues with uninitialized variables. As it's stated in the PHP manual,
Which means that a variable may get a value from the included file, and this value will be used instead of
null
that one expects accessing a non-initialized variable, which may lead to unpredictable results. To avoid that, all variables in a PHP file are best to be initialized before use.Ways to deal with the issue:
Recommended: Declare every variable before use. This way you will see this error only when you actually make a mistake, trying to use a non-existent variable - the very reason this error message exists.
a special case when a variable is defined but is not visible in a function. Functions in PHP have own variable scope, and if you need to use in a function a variable from outside, its value must be passed as a function's parameter:
Suppress the error with null coalescing operator. But remember that this way PHP won't be able to notify you about using wrong variable name.
For the ancient PHP versions (< 7.0) isset() with ternary can be used
Be aware though, that it's still essentially an error suppression, though for just one particular error. So it may prevent PHP from helping you by marking an unitialized variable.
Suppress the error with the @ operator. Left here for the historical reasons but seriously, it just shouldn't happen.
Note: It's strongly recommended to implement just point 1.
Notice: Undefined index / Undefined offset / Warning: Undefined array key
This notice/warning appears when you (or PHP) try to access an undefined index of an array.
Internal arrays
When dealing with internal arrays, that are defined in your code, the attitude should be exactly the same: just initialize all keys before use. this way this error will do its intended job: notify a programmer about a mistake in their code. So the approach is the same:
Recommended: Declare your array elements:
A special case is when some function returns either an array or some other value such as
null
orfalse
. Then it has to be tested before trying to access the array elements, such asOutside arrays
With outside arrays (such as
$_POST
/$_GET
/$_SESSION
or JSON input) the situation is a bit different, because programmer doesn't have the control over such arrays' contents. So checking for some key existence or even assigning a default value for a missing key could be justified.when a PHP script contains an HTML form, it is natural that on the first load there is no form contents. Therefore such a script should check if a form was submitted
some HTML form elements, such as checkboxes, aren't sent to the server if not checked. In this case it is justified to use a null coalescing operator to assign a default value
optional QUERY STRING elements or cookies should be treated the same way
But assignments should be done at the very beginning of the script. Validate all input, assign it to local variables, and use them all the way in the code. So every variable you're going to access would deliberately exist.
Related:
尝试这些
或者,作为一个快速而肮脏的解决方案:
关于会话的注意:
使用会话时,
session_start();
使用sessions。http://php.net/manual/manual/en/features.sessions.php < /a>
Try these
Or, as a quick and dirty solution:
Note about sessions:
When using sessions,
session_start();
is required to be placed inside all files using sessions.http://php.net/manual/en/features.sessions.php
错误显示 @code>@ operator
for docired and defuctor 通知,可以使用专用
@code>@
operator>操作员»隐藏«未定义的变量/索引消息。isset上有一个上行?注意仍然可以记录。并且可以复活- 添加剂,您不应习惯地使用/推荐
- 新来者不会发现这样的错别字。它只是剥夺了这些情况下的PHP通知。添加
-
@
- 与:set_error_handler(“ var_dump”);
如果(ISSET($ _ post [“ shubmit”)))
在您的初始代码中。@
或ISSET
仅在验证功能之后。@
主要是> $ _get
/$ _ post
输入参数,特别是如果它们是可选的。而且,由于这涵盖了大多数此类问题,因此让我们扩展最常见的原因:
$ _ GET
/$ _ POST
/$ _请求
$ count = $ _get [“什么?”];
其次,如果通知没有明显原因,请使用
var_dump
或
print_r
all able 输入库的内容阵列:两者都会揭示您的脚本是否已使用权利或任何参数调用。
替代或另外使用 f12 )并检查网络选项卡的请求和参数:
发布参数和获取输入将分别显示。
对于
$ _ get
参数您也可以窥视query_string
在
中
php有一些规则 cocecce non-standard commine进入超级全球。 Apache也可能会重写。
。
更明显地查看您的浏览器地址栏的获取参数:
http://example.org/script.php?id=5&sort = desc
name = value
对?
问标记是您的查询(get)参数。因此,此URL可能只能产生$ _ get [“ id”]
和$ _ get [stort“”]
。最终检查您的
&lt; form&gt;
and&lt; input&gt;
声明,如果您期望参数但无接收。&lt;输入名称= foo&gt;
id =
或title =
属性不足。method = post
表格应该填充$ _ post
。方法= get
(或排除在外)会产生$ _ get
变量。action = script.php?get = param
,剩余的method = post
copt 字段与$ _post一起。<<<<<<<<<<<<<<<<<<<<<<< /li>$ _ request ['vars']
再次捣碎获取和发布参数。
如果您使用mod_rewrite,则应同时检查
access.log
,并启用rewritelog
要找出缺失参数。$ _文件
$ _文件[“ formName”]
。enctype = multipart/form-data
method = post
在您的&lt; form&gt;
声明中。_FIEL $ _FIEL?
>
$ _ cookie
在setCookie()
之后,永远不会填充数组,而仅在任何后续http请求中。Error display
@
operatorFor undesired and redundant notices, one could use the dedicated
@
operator to »hide« undefined variable/index messages.isset?:
or??
super-supression however. Notices still can get logged. And one may resurrect@
-hidden notices with:set_error_handler("var_dump");
if (isset($_POST["shubmit"]))
in your initial code.@
orisset
only after verifying functionality.@
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 inputFirst thing you do when encountering an undefined index/offset, is check for typos:
$count = $_GET["whatnow?"];
Secondly, if the notice doesn't have an obvious cause, use
var_dump
orprint_r
to verify all input arrays for their curent content: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 theQUERY_STRING
inPHP 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.<input name=FOO>
id=
ortitle=
attribute does not suffice.method=POST
form ought to populate$_POST
.method=GET
(or leaving it out) would yield$_GET
variables.action=script.php?get=param
via $_GET and the remainingmethod=POST
fields in $_POST alongside.$_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 theRewriteLog
to figure out absent parameters.$_FILES
$_FILES["formname"]
.enctype=multipart/form-data
method=POST
in your<form>
declaration.$_COOKIE
$_COOKIE
array is never populated right aftersetcookie()
, but only on any followup HTTP request.通常是由于“不良编程”,并且现在或以后出现错误的可能性。
if(isset($ varname))
,Generally because of "bad programming", and a possibility for mistakes now or later.
if (isset($varname))
, before using it这意味着您正在测试,评估或打印尚未分配任何内容的变量。这意味着您要么有错别字,要么需要检查该变量是否先初始化为某些东西。检查您的逻辑路径,它可以设置在一个路径中,而不是在另一条路径中。
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.
我不想禁用通知,因为这很有帮助,但是我想避免键入太多。
我的解决方案是此功能:
因此,如果我想引用$ name和Echo如果存在,则简单地写:
对于数组元素:
在页面中,如果我想引用$ _request ['name']:
I didn't want to disable notice because it's helpful, but I wanted to avoid too much typing.
My solution was this function:
So if I want to reference to $name and echo if exists, I simply write:
For array elements:
In a page if I want to refer to $_REQUEST['name']:
这是因为变量“ $ user_location”没有得到定义。如果您在内部使用任何(如果循环)来声明“ $ user_location”变量,则还必须具有 else loop 并定义相同的 else。例如:
如果不满足loop ,并且在 else loop '$ user_location'中未定义,则上述代码将创建错误,为。仍要求PHP回声消除该变量。因此,要修改代码,您必须执行以下操作:
It’s 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:
The above code will create an 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:
获取输入字符串的最佳方法是:
这个单线几乎等同于:
如果您绝对想要 string 值,就像:
The best way for getting the input string is:
This one-liner is almost equivalent to:
If you absolutely want a string value, just like:
回答“”为什么它们突然出现?我曾经使用这个脚本多年了,但我从来没有任何问题。”
对于大多数站点在“显示所有错误”的“默认”错误报告下运行非常普遍,但没有'通知'和“已弃用””。这将在php.ini中设置并应用于服务器上的所有站点。这意味着示例中使用的“通知”将被抑制(隐藏),而其他被认为更为关键的错误将显示/录制的
另一个关键设置是可以隐藏的(即
display_errors
设置为“ off”或“ syslog”)。 /code>更改为(根据示例)显示通知和/或在屏幕上更改为
display_errors
(而不是抑制它们/记录它们)更改了?
明显/最简单的答案是,在PHP.Ini中调整了这些设置中的任何一个,或者升级的PHP版本现在正在使用以前使用其他php.ini。那是第一个看的地方。
但是,也可以在
,并且其中任何一个也可以更改。
还有其他复杂性,Web服务器配置可以启用/禁用.htaccess指令,因此,如果您有.htaccess中的指令突然启动/停止工作,则需要检查该指令。
(.htconf / .htaccess假设您正在运行为Apache。如果运行命令行,则不会应用;如果运行IIS或其他WebServer,则需要相应地检查这些配置)
摘要< / strong>
error_reporting
和display_errors
php.ini中的php指令尚未更改,或者您没有从前使用过不同的php.ini。error_reporting
和display_errors
中的指令没有更改error_reporting
和display_errors
php指令已在此处设置。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 todisplay_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
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
error_reporting
anddisplay_errors
php directives in php.ini has not changed, or that you're not using a different php.ini from before.error_reporting
anddisplay_errors
php directives in .htconf (or vhosts etc) have not changederror_reporting
anddisplay_errors
php directives in .htaccess have not changederror_reporting
anddisplay_errors
php directives have been set there.快速修复是将您的变量分配给代码顶部的null:
The quick fix is to assign your variable to null at the top of your code:
为什么会发生这种情况?
随着时间的流逝,PHP已成为一种更加安全的语言。默认情况下,默认情况下以前关闭的设置将打开。一个完美的例子是
e_strict
,默认情况下默认打开了 PHP 5.4.0 。此外,根据PHP文档,默认情况下,
e_notice
在文件 php.ini 中被禁用。 PHP文档建议将其打开以进行调试目的。但是,当我从Ubuntu存储库中下载PHP并从Bitnami的Windows堆栈中下载时,我会看到其他东西。请注意,
error_reporting
实际上默认设置为生产值,而不是默认为“默认”值。这有点令人困惑,并且没有在 php.ini 之外记录,因此我有 不是 在其他分布上验证了这一点。但是,要回答您的问题,此错误现在没有弹出时弹出,因为:
您安装了php,新的默认设置的记录不足,但不排除
e_notice
。 /p>e_notice
警告如未定义的变量和未定义的索引实际上有助于使您的代码更清洁,更安全。我可以告诉你,几年前,保持e_notice
使我迫使我声明我的变量。它使学习C变得更容易C。在C中,没有声明变量更大得多。我该怎么办?
通过复制“默认值”
e_all&amp; 〜E_NOTICE&amp; 〜E_STRICT&amp; 〜E_DEPRECTADED
并用当前在error_reporting =
中equals sign之后替换了它。如果使用CGI或FPM,请重新启动Apache或PHP。确保您正在编辑“正确” php.ini 文件。如果您运行php-fpm,如果运行PHP-CGI等,则正确的是Apache,如果您使用Apache,FPM或PHP-FPM运行PHP。非常困难的编辑,然后可能是您最好的选择。关闭文件或文件夹级别上的e_notice 。如果您有一些遗留代码,但希望以“正确”的方式做事,这可能是可取的。为此,您应该咨询Apache&nbsp; 2,nginx或任何选择的服务器。在Apache中,您将在
&lt; directory&gt;
的内部使用php_value
。。
重写您的代码以使其更加清洁。如果您在转到生产环境时需要执行此操作,或者不希望某人看到您的错误,请确保您禁用任何错误显示,并且只有记录 您的错误(请参阅
display_errors
和log_errors
在php.ini和您的服务器设置中)。在选项3上扩展:这是理想的。如果您可以走这条路线,那应该。如果您最初不走这条路线,请考虑最终通过在开发环境中测试您的代码来移动这条路线。当您使用它时,请摆脱
〜E_STRICT
和〜E_DEPRECED
以查看将来可能出问题的地方。您将看到很多陌生的错误,但是当您将来需要升级PHP时,这将阻止您遇到任何不愉快的问题。错误是什么意思?
未定义的变量:my_variable_name
- 当使用前未定义变量时,就会发生这种情况。当执行PHP脚本时,它在内部仅假定一个空值。但是,在定义变量之前,您需要在哪种情况下检查它?最终,这是“草率代码”的论点。作为开发人员,我可以告诉您,当我看到一个开源项目时,我会喜欢它,该项目将变量定义为高度范围,因为它们可以定义它们。它可以更轻松地判断将来会弹出哪些变量,并使阅读/学习代码更容易。未定义的索引:my_index
- 当您尝试访问数组中的值并且不存在时,就会发生这种情况。为了防止此错误,请执行有条件的检查。另一个选择是在功能顶部声明一个空数组。这并非总是可能的。
(附加提示)
vim
的人:)。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 file php.ini. PHP documentation recommends 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.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:
You installed PHP and the new default settings are somewhat poorly documented but do not exclude
E_NOTICE
.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, keepingE_NOTICE
enabled forced me to declare my variables. It made it a LOT easier to learn C. In C, not declaring variables is much bigger of a nuisance.What can I do about it?
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 inerror_reporting =
. Restart Apache, or PHP if using CGI or FPM. Make sure you are editing the "right" php.ini file. 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.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 Apache 2, Nginx, or whatever your server of choice is. In Apache, you would usephp_value
inside of<Directory>
.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
andlog_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.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.Another option is to declare an empty array at the top of your function. This is not always possible.
(Additional tip)
vim
person these days :).我曾经诅咒此错误,但是提醒您逃脱用户输入可能会有所帮助。
例如,如果您认为这很聪明,速记代码:
...想一想!一个更好的解决方案是:(
我使用自定义
html()
函数逃脱字符,您的里程可能会有所不同)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:
...Think again! A better solution is:
(I use a custom
html()
function to escape characters, your mileage may vary)在php 7.0中,现在可以使用 null null colesescing操作员
: =“ http://php.net/manual/en/migration70.new-features.php#migration70.new-features.new-features.null-coalesce-op” rel =“ nofollow noreferrer”>“ nofollow noreferrer”>
In PHP 7.0 it's now possible to use the null coalescing operator:
Is equals to:
PHP manual PHP 7.0
我使用自己的有用功能, exst(),它一直自动声明变量。
您的代码将是 -
I use my own useful function, exst(), all time which automatically declares variables.
Your code will be -