“注意:未定义的变量”:“注意:未定义的索引”警告:未定义的数组键&quot&quitd&quitd:&quote&quits;使用PHP

发布于 2025-02-07 19:49:01 字数 1435 浏览 7 评论 0 原文

我正在运行一个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"];

这些错误消息的含义是什么?

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

我该如何修复它们?


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

相关的元讨论:

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

Warning: Undefined array key "my_index" in 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:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(29

青春有你 2025-02-14 19:49:02

在非常简单的语言中:

错误是您使用的是变量 $ 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.

好倦 2025-02-14 19:49:02

保持简单:

<?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 the array index. Nice
?>

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 the array index. Nice
?>
满身野味 2025-02-14 19:49:02

未定义的索引意味着您要求使用不可用的数组索引的数组中。例如,

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

未定义的变量意味着您完全使用了现有变量,或者未通过该名称定义或初始化的变量。例如,

<?php print_r($myvar); ?>

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

php> echo array_key_exists(1, $myarray);

An undefined index means in an array you requested for an unavailable array index. For example,

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

An undefined variable means you have used completely not an existing variable or which is not defined or initialized by that name. For example,

<?php print_r($myvar); ?>

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> echo array_key_exists(1, $myarray);
本宫微胖 2025-02-14 19:49:02

关于这个问题的这一部分:

为什么它们突然出现?我曾经使用这个脚本多年了,但我从来没有任何问题。

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

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

  2. 您已删除或介绍了一些代码(可能是在依赖项中),该代码在运行时使用 ini_set()或 error_reporting()(在代码)

  3. 您更改了Web服务器配置(在此处假设Apache): .htaccess 文件和VHOST配置也可以操纵PHP设置。

  4. 通常不会显示/报告显示(请参阅 php手册
    因此,在设置服务器时,由于某种原因无法加载PHP.Ini文件(文件权限??),并且您在默认设置上。后来,(偶然地)解决了“错误”,现在它可以加载正确的php.ini文件,其中包括error_reporting设置以显示通知。< / p>

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.

凉风有信 2025-02-14 19:49:02

使用 ternary oterator ,可读和清洁:

pre php 7

如果设置为另一个变量的值您需要的值):

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

php 7+

相同,除了使用无效的合并操作员。不再需要在内置的情况下调用 isset(),也不需要提供变量以返回的变量,因为假定要返回被检查的变量的值:

$newVariable = $thePotentialData ?? null;

都/strong>将在OP的问题中停止通知,并且 act ot 的确切等同是:

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

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

echo: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
    }
}

以上将与数组(包括会话等)相同,替换了用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):

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

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:

$newVariable = $thePotentialData ?? null;

Both will stop the Notices from the OP's 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 operator'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.

谷夏 2025-02-14 19:49:02

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

class Person
{
    protected $firstName;
    protected $lastName;

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

        // Incorrect
        $lastName = $last;

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

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;
    }
}
青朷 2025-02-14 19:49:02

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

IE:

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

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

即:

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

或在循环中:

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上的其他内容,情况对病例敏感。

请咨询堆栈上的引物Q&amp; a是:

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:

圈圈圆圆圈圈 2025-02-14 19:49:02

提交 html 表格之后,不存在的变量的一个常见原因是&lt; form&gt; tag:

示例:element: element:element:element:element:element:element:element:element:不包含在&lt; form&gt;

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

示例中:element现在包含在&lt; form&gt;

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

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>
夜血缘 2025-02-14 19:49:02

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

处理这些问题的最佳方法是开发期间的设置错误报告。

要设置错误报告:

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

在生产服务器上,错误报告已关闭,因此,我们没有收到这些错误。

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

为了摆脱此错误,我们看到以下示例:

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

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

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

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

这不会打扰任何程序逻辑,即使 $ 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:

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 an 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 an error as $my is not 9.
}
echo $test;

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.

过潦 2025-02-14 19:49:02

我问了一个问题,并将其转介给了这篇文章:

这个问题在这里已经有一个答案:

“通知:未定义变量”,“通知:未定义的索引”和“通知:
使用php

的未定义偏移”

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

这是错误:

“在此处输入图像说明”

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

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

我认为问题是我正在编写是否为变量 $ city 的条件,这不是关键,而是 $ key =&gt中的值; $ City 。首先,您能确认这是警告的原因吗?其次,如果那是问题,为什么我不能基于值编写条件?是否必须与我需要编写条件的钥匙?

更新1:问题是,当执行 $ cotityCountraray [$ key] 时,有时 $ key 对应于 $ $ citiesCountarRay中不存在的键< /code>数组,但基于我的循环数据并非总是如此。我需要设置条件,以便如果 $ key 存在数组中,则运行代码,否则请跳过它。

更新2:这是我使用 array_key_exists()

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

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:

enter image description here

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)){
白馒头 2025-02-14 19:49:02

可能您一直在使用旧的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.

つ低調成傷 2025-02-14 19:49:02

如果要将数据发送到API,只需使用 isset() :

if(isset($_POST['param'])){
    $param = $_POST['param'];
} else {
    # Do something else
}

如果是由于会话是错误的,请确保您已经正确启动了会话。

If you are sending data to an API, simply use isset():

if(isset($_POST['param'])){
    $param = $_POST['param'];
} else {
    # Do something else
}

If it is an error is because of a session, make sure you have started the session properly.

泅人 2025-02-14 19:49:02

这些通知是因为您没有使用过的变量定义 my_index 键没有在 $ my_array 变量中存在。

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

解决错误:

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

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)
阳光的暖冬 2025-02-14 19:49:02

在处理文件时,需要使用适当的副类型和邮政方法,如果未包含在表单中,这将触发未定义的索引通知。

该手册列出以下基本语法:

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

?>

参考:

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:

忘年祭陌 2025-02-14 19:49:02

在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 if the variable is defined or undefined
// Isset() does not check that variable has a true or false value
// But it checks the null value of a variable
if(isset($my_variable_name)){

}

简单的解释

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

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

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!

// 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 if the variable is defined or undefined
// Isset() does not check that variable has a true or false value
// But it checks the null value of a variable
if(isset($my_variable_name)){

}

Simple Explanation

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

// It will check if the variable is defined or not and if the variable has a null value.
if(isset($unDefineVariable)){
    echo "true";
}else{
    echo "false";
}
秉烛思 2025-02-14 19:49:01

此错误消息是指在访问不存在的变量(或数组元素)时发现错别字或错误的PHP程序员。因此,一个好的程序员:

  1. 确保每个变量或数组键已经通过使用时间来定义。如果需要在函数内使用变量,则必须将其作为参数传递给该函数。
  2. 对此错误付出了重视,并继续修复它,就像其他任何错误一样。可能表明拼写错误,或者某些过程没有返回应该返回的数据。
  3. 只有在极少数情况下,当事物不在程序员的控制之下时,才能添加代码以规避此错误。但绝不应该是一种无意识的习惯。

注意 /警告:未定义的变量

,尽管PHP不需要变量声明,但它确实建议它,以避免某些安全漏洞或错误,在这些漏洞或错误中,人们忘记将值给出一个可变量的值,该变量将在以后在脚本中使用。在未确定变量的情况下,PHP的作用是 e_warning 级别的错误。

该警告可帮助程序员发现拼写错误的变量名称或类似的错误(例如,将变量分配给评估为false的条件的内部值)。此外,还有其他可能的问题具有非初始化的变量。因为它是在PHP手册中,

依靠非初始化变量的默认值是有问题的,因为将一个文件包括在另一个文件中,该文件使用相同的变量名称。

这意味着变量可以从随附的文件中获取一个值,并且将使用此值代替 null ,人们期望访问非启用变量,这可能会导致无法预测的结果。为了避免这种情况,最好在使用前初始化PHP文件中的所有变量。

处理问题的方法:

  1. 推荐:在使用前声明每个变量。这样,只有当您实际犯错,尝试使用不存在的变量时,您才会看到此错误 - 此错误消息存在。

      //初始化变量
     $ value =“”; //初始化值; 0对于int,[]用于数组,等等。
     echo $ value; //没有错误
     Echo $ vaule; //错误查明一个拼写错误的变量名称
     
  • 定义变量但在函数中不可见的特殊情况。 PHP中的功能具有自己的 variable范围,如果您需要在函数中使用一个来自外部的变量,其值必须作为函数参数传递:

     功能测试($ param){
        返回$ param + 1; 
    }
    $ var = 0;
    回声测试($ var); //现在可以在$ param的内部访问$ var的值
     
  1. 抑制NULL合并运算符的误差。但是请记住,这种方式PHP将无法通知您有关使用错误的变量名称的通知。

      //零合并操作员
     echo $ value ?? '';
     

    对于古代PHP版本(&lt; 7.0)带有三元的Isset()可以使用

      echo isset($ value)? $ value:'';
     

    请注意,尽管这只是一个特定的错误,但它本质上仍然是一个错误抑制。因此,它可能会通过标记单位化变量来阻止PHP帮助您。

  2. @ operator 来抑制错误。出于历史原因而留在这里,但确实不应该发生。

注意:< / strong>强烈建议实现点1。

注意:未定义的索引 /未定义的偏移 /警告:未定义的数组键,

当您(或PHP)尝试访问一个不确定的索引时,会出现此通知 /警告大批。

内部数组

在处理内部数组时(在您的代码中定义的内部数组)时,态度应完全相同:只需在使用前初始化所有键即可。这样,此错误将执行其预期工作:通知程序员有关其代码中的错误。因此方法是相同的:

推荐:声明您的数组元素:

    //Initializing a variable
    $array['value'] = ""; //Initialization value; 0 for int, [] for array, etc.
    echo $array['value']; // no error
    echo $array['vaule']; // an error indicates a misspelled key

特殊情况是某些函数返回数组或其他值时,例如 null > false 。然后必须在尝试访问数组元素之前对其进行测试,例如

$row = $stmt->fetch();
if ($row) { // the record was found and can be worked with
    echo $row['name']; 
}

带有外部数组的外部数组

(例如 $ _ post < / code> / $ _ get < / code> / code> / $ _ sessign < /code>或json输入)情况有些不同,因为程序员对此类数组的内容没有控制权。因此,可以证明检查某些密钥存在,甚至分配缺少密钥的默认值。

  • 当PHP脚本包含HTML表单时,自然而然的是,在第一个载荷上没有形式内容。因此,这样的脚本应检查是否提交表格

      //为邮票检查请求方法
      if($ _server ['request_method'] ==='post'){
          //处理表格
      }
      //获取表单 /链接检查重要字段
      if(isset($ _ get ['search'])){
          //处理表格
      }
     
  • 某些HTML表单元素(例如复选框)如果未检查,则不会将其发送到服务器。在这种情况下

      $ cansed = $ _post ['enter'] ??错误的;
     
  • 在这种
      $ limit = $ _get ['limit'] ?? 20;
      $ them = $ _cookie ['theme']? '光';
     

但分配应在脚本的最初完成。 验证所有输入,将其分配给本地变量,然后在代码中一直使用它们。因此,您将要访问的每个变量都会故意存在。

相关:

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:

  1. Makes sure that every variable or array key is already defined by the time it's going to be used. In case a variable is needed to be used inside a function, it must be passed to that function as a parameter.
  2. Pays attention to this error and proceeds to fix it, just like with any other error. It may indicate a spelling error or that some procedure didn't return the data it should.
  3. Only on a rare occasion, when things are not under the programmer's control, a code can be added to circumvent this error. But by no means it should be a mindless habit.

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,

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.

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:

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

     //Initializing a variable
     $value = ""; //Initialization value; 0 for int, [] for array, etc.
     echo $value; // no error
     echo $vaule; // an error pinpoints a misspelled variable name
    
  • 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:

    function test($param) {
        return $param + 1; 
    }
    $var = 0;
    echo test($var); // now $var's value is accessible inside through $param
    
  1. 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.

     // Null coalescing operator
     echo $value ?? '';
    

    For the ancient PHP versions (< 7.0) isset() with ternary can be used

     echo isset($value) ? $value : '';
    

    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.

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

    //Initializing a variable
    $array['value'] = ""; //Initialization value; 0 for int, [] for array, etc.
    echo $array['value']; // no error
    echo $array['vaule']; // an error indicates a misspelled key

A special case is when some function returns either an array or some other value such as null or false. Then it has to be tested before trying to access the array elements, such as

$row = $stmt->fetch();
if ($row) { // the record was found and can be worked with
    echo $row['name']; 
}

Outside 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

      // for POST forms check the request method
      if ($_SERVER['REQUEST_METHOD'] === 'POST') {
          // process the form
      }
      // for GET forms / links check the important field
      if (isset($_GET['search'])) {
          // process the form
      }
    
  • 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

      $agreed = $_POST['terms'] ?? false;
    
  • optional QUERY STRING elements or cookies should be treated the same way

      $limit = $_GET['limit'] ?? 20;
      $theme = $_COOKIE['theme'] ?? 'light';
    

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:

弃爱 2025-02-14 19:49:01

尝试这些

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

Q2:使用isset(),使用任何可疑变量之前使用iseet()条件。

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

关于会话的注意:

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:

梦醒时光 2025-02-14 19:49:01

错误显示 @code>@ operator

for docired and defuctor 通知,可以使用专用 @code>@ operator>操作员»隐藏«未定义的变量/索引消息。

$var = @($_GET["optional_param"]);
  • 通常会灰心。新来者倾向于过度使用它。
  • 对于在应用程序逻辑中深处的代码(忽略您不应该的未确定变量),例如函数参数或循环中的代码非常不合适。
  • isset上有一个上行?注意仍然可以记录。并且可以复活@ - 与: set_error_handler(“ var_dump”);
    • 添加剂,您不应习惯地使用/推荐如果(ISSET($ _ post [“ shubmit”)))在您的初始代码中。
    • 新来者不会发现这样的错别字。它只是剥夺了这些情况下的PHP通知。添加@ ISSET 仅在验证功能之后。
    • 首先修复原因。不是通知。

  • @ 主要是> $ _get / $ _ post 输入参数,特别是如果它们是可选的

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

$ _ GET / $ _ POST / $ _请求

  • undefined Input p>遇到未定义的索引/偏移时要做的第一件事是检查错别字:
    $ count = $ _get [“什么?”];

    • 这是一个预期的关键名称,并且在上显示页面请求?
    • 变量名称数组表示在php中对案例敏感。
  • 其次,如果通知没有明显原因,请使用 var_dump print_r all able 输入库的内容阵列:

      var_dump($ _ get);
    var_dump($ _ post);
    // print_r($ _请求);
     

    两者都会揭示您的脚本是否已使用权利或任何参数调用。

  • 替代或另外使用 f12 )并检查网络选项卡的请求和参数:

    “浏览器开发人员工具/网络TAB”

    发布参数和获取输入将分别显示。

  • 对于

    $ _ get 参数您也可以窥视 query_string

      print_r($ _ server);
     

    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 = 属性不足。
    • a method = post 表格应该填充 $ _ post
    • 方法= get (或排除在外)会产生 $ _ get 变量。
    • 表格也有可能通过$ _get提供 action = script.php?get = param ,剩余的 method = post copt 字段与$ _post一起。<<<<<<<<<<<<<<<<<<<<<<< /li>
    • 使用现代PHP配置(≥5.6),它已经变成可行)使用 $ _ request ['vars'] 再次捣碎获取和发布参数。

  • 如果您使用mod_rewrite,则应同时检查 access.log ,并启用 rewritelog 要找出缺失参数。

$ _文件

  • 将相同的理智检查应用于文件上传和 $ _文件[“ formName”]
  • 此外,请检查 enctype = multipart/form-data
  • 以及 method = post 在您的&lt; form&gt; 声明中。
  • 另请参阅: php undfined Index错误$ _FIEL $

_FIEL $ _FIEL? >

  • $ _ cookie setCookie()之后,永远不会填充数组,而仅在任何后续http请求中。
  • 此外,它们的有效性时间可能会限制对子域或单个路径,用户和浏览器可以拒绝或删除它们。

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:

    browser developer tools / network tab

    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.
太傻旳人生 2025-02-14 19:49:01

通常是由于“不良编程”,并且现在或以后出现错误的可能性。

  1. 如果是一个错误,请先对变量进行适当的分配:$ varname = 0;
  2. 如果有时仅定义它,请对其进行测试: if(isset($ varname))
  3. 如果是因为您拼写错误,请在使用它之前使用它,只是正确,
  4. 甚至可以转弯您中的警告 php-settings

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
可爱暴击 2025-02-14 19:49:01

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

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.

雨夜星沙 2025-02-14 19:49:01

我不想禁用通知,因为这很有帮助,但是我想避免键入太多。

我的解决方案是此功能:

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

因此,如果我想引用$ name和Echo如果存在,则简单地写:

<?= ifexists('name') ?>

对于数组元素:

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

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

<?= ifexistsidx($_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:

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 a page if I want to refer to $_REQUEST['name']:

<?= ifexistsidx($_REQUEST, 'name') ?>
千と千尋 2025-02-14 19:49:01

这是因为变量“ $ user_location”没有得到定义。如果您在内部使用任何(如果循环)来声明“ $ user_location”变量,则还必须具有 else loop 并定义相同的 else。例如:

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

如果不满足loop ,并且在 else loop '$ user_location'中未定义,则上述代码将创建错误,为。仍要求PHP回声消除该变量。因此,要修改代码,您必须执行以下操作:

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

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:

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

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:

$a = 10;
if($a == 5) {
    $user_location='Paris';
}
else {
    $user_location='SOMETHING OR BLANK';
}
echo $user_location;
Saygoodbye 2025-02-14 19:49:01

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

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

The best way for getting the 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 a string value, just like:

$value = (string)filter_input(INPUT_POST, 'value');
緦唸λ蓇 2025-02-14 19:49:01

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

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

另一个关键设置是可以隐藏的(即 display_errors 设置为“ off”或“ syslog”)

。 /code>更改为(根据示例)显示通知和/或在屏幕上更改为 display_errors (而不是抑制它们/记录它们

)更改了?

明显/最简单的答案是,在PHP.Ini中调整了这些设置中的任何一个,或者升级的PHP版本现在正在使用以前使用其他php.ini。那是第一个看的地方。

但是,也可以在

  • .htconf(WebServer配置,包括VHOST和子配置)中覆盖这些设置*
  • .htaccess
  • 在PHP代码本身中

,并且其中任何一个也可以更改。

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

(.htconf / .htaccess假设您正在运行为Apache。如果运行命令行,则不会应用;如果运行IIS或其他WebServer,则需要相应地检查这些配置)

摘要< / strong>

  • 检查检查 error_reporting display_errors php.ini中的php指令尚未更改,或者您没有从前使用过不同的php.ini。
  • .htconf中的php指令(或vhosts等)没有更改
  • 检查 error_reporting display_errors 中的指令没有更改
  • .htaccess
  • 。可能是一个无关的图书馆;查看 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 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.
扭转时空 2025-02-14 19:49:01

快速修复是将您的变量分配给代码顶部的null:

$user_location = null;

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

$user_location = null;
携余温的黄昏 2025-02-14 19:49:01

为什么会发生这种情况?

随着时间的流逝,PHP已成为一种更加安全的语言。默认情况下,默认情况下以前关闭的设置将打开。一个完美的例子是 e_strict ,默认情况下默认打开了 PHP 5.4.0

此外,根据PHP文档,默认情况下, e_notice 在文件 php.ini 中被禁用。 PHP文档建议将其打开以进行调试目的。但是,当我从Ubuntu存储库中下载PHP并从Bitnami的Windows堆栈中下载时,我会看到其他东西。

; 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 之外记录,因此我有 不是 在其他分布上验证了这一点。

但是,要回答您的问题,此错误现在没有弹出时弹出,因为:

  1. 您安装了php,新的默认设置的记录不足,但不排除 e_notice 。 /p>

  2. e_notice 警告如未定义的变量和未定义的索引实际上有助于使您的代码更清洁,更安全。我可以告诉你,几年前,保持 e_notice 使我迫使我声明我的变量。它使学习C变得更容易C。在C中,没有声明变量更大得多。

我该怎么办?

  1. 通过复制“默认值” 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。非常困难的编辑,然后可能是您最好的选择。

  2. 关闭文件或文件夹级别上的e_notice 。如果您有一些遗留代码,但希望以“正确”的方式做事,这可能是可取的。为此,您应该咨询Apache&nbsp; 2,nginx或任何选择的服务器。在Apache中,您将在&lt; directory&gt; 的内部使用 php_value

  3. 重写您的代码以使其更加清洁。如果您在转到生产环境时需要执行此操作,或者不希望某人看到您的错误,请确保您禁用任何错误显示,并且只有记录 您的错误(请参阅 display_errors log_errors 在php.ini和您的服务器设置中)。

在选项3上扩展:这是理想的。如果您可以走这条路线,那应该。如果您最初不走这条路线,请考虑最终通过在开发环境中测试您的代码来移动这条路线。当您使用它时,请摆脱 〜E_STRICT 〜E_DEPRECED 以查看将来可能出问题的地方。您将看到很多陌生的错误,但是当您将来需要升级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';

(附加提示)

  • 当我遇到这些问题和其他问题时,我使用 netbeanss idide (免费),它给了我一个主机警告和通知。其中一些提供了非常有用的技巧。这不是要求,除了大型项目外,我不再使用IDE。这些天我更像是一个 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.

; 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. In C, 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 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.

  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 Apache 2, 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 NetBeanss 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 :).
清君侧 2025-02-14 19:49:01

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

例如,如果您认为这很聪明,速记代码:

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

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

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

我使用自定义 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:

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

橘香 2025-02-14 19:49:01

在php 7.0中,现在可以使用 null null colesescing操作员

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

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

: =“ 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:

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

Is equals to:

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

PHP manual PHP 7.0

倚栏听风 2025-02-14 19:49:01

我使用自己的有用功能, 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;
}

I use my own useful function, exst(), all time which automatically declares 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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文