PHP 错误:注意:未定义索引:

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4465728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:06:50  来源:igfitidea点击:

PHP error: Notice: Undefined index:

phpvariablesindexingundefined

提问by PHPNOOB

I am working on a shopping cart in PHP and I seem to be getting this error "Notice: Undefined index:" in all sorts of places. The error refers to the similar bit of coding in different places. For example I have a piece of coding that calculates a package price with the months a user decides to subscribe. I have the following variables where the errors refers to:

我正在用 PHP 处理购物车,但似乎在各种地方都收到此错误“注意:未定义索引:”。错误是指不同地方编码的相似位。例如,我有一段代码可以计算用户决定订阅的月份的套餐价格。我有以下错误所指的变量:

    $month = $_POST['month'];
    $op = $_POST['op'];

The $month variable is the number the user inputs in a form, and the $op variable is different packages whose value are stored in a vriable that a user selects from radio buttons on the form.

$month 变量是用户在表单中输入的数字,$op 变量是不同的包,其值存储在用户从表单上的单选按钮中选择的变量中。

I hope that is clear in some way.

我希望这在某种程度上是清楚的。

Thank You

谢谢你

EDIT: Sorry forgot to mention that they do go away when the user submits the data. But when they first come to the page it displays this error. How I can get rid of it so it doesnt display it?

编辑:抱歉忘了提到当用户提交数据时它们会消失。但是当他们第一次来到页面时,它会显示这个错误。我怎样才能摆脱它所以它不显示它?

--

——

This is the code:

这是代码:

<?php
    $pack_1 = 3;
    $pack_2 = 6;
    $pack_3 = 9;
    $pack_4 = 12;
    $month = $_POST['month'];
    $op = $_POST['op'];
    $action = $_GET['action'];

    if ( $op == "Adopter" ) {
       $answer = $pack_1 * $month;
    }

    if ( $op == "Defender" ) {
      $answer = $pack_2 * $month;
    }

    if ( $op == "Protector" ) {
      $answer = $pack_3 * $month;
    }

    if ( $op == "Guardian" ) {
      $answer = $pack_4 * $month;
    }

    switch($action) {   
        case "adds":
            $_SESSION['cart'][$answer][$op];
            break;
    }
?>  

回答by meagar

You're attempting to access indicies within an array which are not set. This raises a notice.

您正在尝试访问未设置的数组中的索引。这引发了一个通知。

Mostly likely you're noticing it now because your code has moved to a server where php.ini has error_reportingset to include E_NOTICE. Either suppress notices by setting error_reporting to E_ALL & ~E_NOTICE(not recommended), or verify that the index exists before you attempt to access it:

很可能您现在已经注意到它,因为您的代码已移至 php.ini 已error_reporting设置为 include的服务器E_NOTICE。通过将 error_reporting 设置为E_ALL & ~E_NOTICE(不推荐)来抑制通知,或者在尝试访问索引之前验证索引是否存在:

$month = array_key_exists('month', $_POST) ? $_POST['month'] : null;

回答by DeaconDesperado

Are you putting the form processor in the same script as the form? If so, it is attempting to process before the post values are set (everything is executing).

您是否将表单处理器放在与表单相同的脚本中?如果是这样,它会尝试在设置 post 值之前进行处理(一切都在执行)。

Wrap all the processing code in a conditional that checks if the form has even been sent.

将所有处理代码包装在检查表单是否已发送的条件中。

if(isset($_POST) && array_key_exists('name_of_your_submit_input',$_POST)){
//process form!
}else{
//show form, don't process yet!  You can break out of php here and render your form
}

Scripts execute from the top down when programming procedurally. You need to make sure the program knows to ignore the processing logic if the form has not been sent. Likewise, after processing, you should redirect to a success page with something like

程序化编程时,脚本自上而下执行。如果表单尚未发送,您需要确保程序知道忽略处理逻辑。同样,处理后,您应该重定向到成功页面,其中包含类似内容

header('Location:http://www.yourdomainhere.com/formsuccess.php');

I would not get into the habit of supressing notices or errors.

我不会养成抑制通知或错误的习惯。

Please don't take offense if I suggest that if you are having these problems and you are attempting to build a shopping cart, that you instead utilize a mature ecommerce solution like Magento or OsCommerce. A shopping cart is an interface that requires a high degree of security and if you are struggling with these kind of POST issues I can guarantee you will be fraught with headaches later. There are many great stable releases, some as simple as mere object models, that are available for download.

如果我建议您在遇到这些问题并尝试构建购物车时,请不要生气,建议您使用成熟的电子商务解决方案,如 Magento 或 OsCommerce。购物车是一个需要高度安全的界面,如果您正在为这些 POST 问题苦苦挣扎,我可以保证您以后会很头疼。有许多出色的稳定版本可供下载,有些像单纯的对象模型一样简单。

回答by Mchl

Obviously $_POST['month'] is not set. Maybe there's a mistake in your HTML form definition, or maybe something else is causing this. Whatever the cause, you should always check if a variable exists before using it, so

显然 $_POST['month'] 没有设置。也许您的 HTML 表单定义中有错误,或者其他原因导致了这种情况。不管是什么原因,你应该总是在使用变量之前检查它是否存在,所以

if(isset($_POST['month'])) {
   $month = $_POST['month'];
} else {
   //month is not set, do something about it, raise an error, throw an exception, orwahtever
}

回答by mario

How I can get rid of it so it doesnt display it?

我怎样才能摆脱它所以它不显示它?

People here are trying to tell you that it's unprofessional (and it is), but in your case you should simply add following to the start of your application:

这里的人试图告诉您这是不专业的(而且确实如此),但在您的情况下,您只需在应用程序的开头添加以下内容:

 error_reporting(E_ERROR|E_WARNING);

This will disable E_NOTICE reporting. E_NOTICES are not errors, but notices, as the name says. You'd better check this stuff out and proof that undefined variables don't lead to errors. But the common case is that they are just informal, and perfectly normal for handling form input with PHP.

这将禁用 E_NOTICE 报告。E_NOTICES 不是错误,而是通知,顾名思义。你最好检查一下这些东西并证明未定义的变量不会导致错误。但常见的情况是它们只是非正式的,并且对于使用 PHP 处理表单输入是完全正常的。

Also, next time Google the error message first.

另外,下次谷歌时先搜索错误信息。

回答by mohammad

This are just php notice messages,it seems php.ini configurations are not according vtiger standards, you can disable this message by setting error reportingto E_ALL & ~E_NOTICEin php.iniFor example error_reporting(E_ALL&~E_NOTICE)and then restart apacheto reflect changes.

这只是php的通知信息,看来php.ini的配置不符合vtiger标准,你可以通过在php.ini中将错误报告设置为E_ALL & ~E_NOTICE来禁用此信息, 例如,然后重新启动apache以反映更改。error_reporting(E_ALL&~E_NOTICE)

回答by helderk

Try this:

尝试这个:

$month = ( isset($_POST['month']) ) ? $_POST['month'] : '';

$op = ( isset($_POST['op']) ) ? $_POST['op'] : '';

回答by RandheerPratapSingh

<?php
if ($_POST['parse_var'] == "contactform"){


        $emailTitle = 'New Email From KumbhAqua';
        $yourEmail = '[email protected]';

        $emailField = $_POST['email'];
        $nameField = $_POST['name'];
        $numberField = $_POST['number'];
        $messageField = $_POST['message'];  

        $body = <<<EOD
<br><hr><br>
    Email: $emailField <br /> 
    Name:  $nameField <br />
    Message: $messageField <br />


EOD;

    $headers = "from: $emailField\r\n";
    $headers .= "Content-type: text/htmml\r\n";
    $success =  mail("$yourEmail", "$emailTitle", "$body", "$headers");

    $sent ="Thank You ! Your Message Has Been sent.";

}

?>


 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>:: KumbhAqua ::</title>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
        <link rel="stylesheet" href="style1.css" type="text/css">

</head>

<body>
    <div class="container">
        <div class="mainHeader">
            <div class="transbox">

              <p><font color="red" face="Matura MT Script Capitals" size="+5">Kumbh</font><font face="Matura MT Script Capitals" size="+5" color=                                                                           "skyblue">Aqua</font><font color="skyblue"> Solution</font></p>
              <p ><font color="skyblue">Your First Destination for Healthier Life.</font></p>
                    <nav><ul>
                        <li> <a href="KumbhAqua.html">Home</a></li>
                        <li> <a href="aboutus.html">KumbhAqua</a></li>
                        <li> <a href="services.html">Products</a></li>
                        <li  class="active"> <a href="contactus.php">ContactUs</a></li>

                    </ul></nav>
                </div>
            </div>
        </div>
                    <div class="main">
                        <div class="mainContent">
                            <h1 style="font-size:28px; letter-spacing: 16px; padding-top: 20px; text-align:center; text-transform: uppercase; color:                                    #a7a7a7"><font color="red">Kumbh</font><font color="skyblue">Aqua</font> Symbol of purity</h1>
                                <div class="contactForm">
                                    <form name="contactform" id="contactform" method="POST" action="contactus.php" >
                                        Name :<br />
                                        <input type="text" id="name" name="name" maxlength="30" size="30" value="<?php echo "nameField"; ?>" /><br />
                                         E-mail :<br />
                                        <input type="text" id="email" name="email" maxlength="50" size="50" value="<?php echo "emailField"; ?>" /><br />
                                         Phone Number :<br />
                                        <input type="text" id="number" name="number" value="<?php echo "numberField"; ?>"/><br />
                                         Message :<br />
                                        <textarea id="message" name="message" rows="10" cols="20" value="<?php echo "messageField"; ?>" >Some Text...                                        </textarea>
                                        <input type="reset" name="reset" id="reset" value="Reset">
                                        <input type="hidden" name="parse_var" id="parse_var" value="contactform" />
                                        <input type="submit" name="submit" id="submit" value="Submit"> <br />

                                        <?php  echo "$sent"; ?>

                                    </form>
                                        </div>  
                            <div class="contactFormAdd">

                                    <img src="Images/k1.JPG" width="200" height="200" title="Contactus" />
                                    <h1>KumbhAqua Solution,</h1>
                                    <strong><p>Saraswati Vihar Colony,<br />
                                    New Cantt Allahabad, 211001
                                    </p></strong>
                                    <b>DEEPAK SINGH &nbsp;&nbsp;&nbsp; RISHIRAJ SINGH<br />
                                    8687263459 &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;8115120821 </b>

                            </div>
                        </div>
                    </div>

                            <footer class="mainFooter">
                            <nav>
                            <ul>
                                <li> <a href="KumbhAqua.html"> Home </a></li>
                                <li> <a href="aboutus.html"> KumbhAqua </a></li>
                                <li> <a href="services.html"> Products</a></li>
                                <li class="active"> <a href="contactus.php"> ContactUs </a></li>
                            </ul>
                                <div class="r_footer">


          Copyright &copy; 2015 <a href="#" Title="KumbhAqua">KumbhAqua.in</a> &nbsp;&nbsp;&nbsp;&nbsp; Created and Maintained By-   <a title="Randheer                                                                                                                                                                                                                             Pratap Singh "href="#">RandheerSingh</a>                                                                            </div>  
                            </nav>
                            </footer>
    </body>
</html> 

    enter code here

回答by Douglas Michalek

I did define all the variables that was the first thing I checked. I know it's not required in PHP, but old habits die hard. Then I sanatized the info like this:

我确实定义了所有变量,这是我检查的第一件事。我知道它在 PHP 中不是必需的,但是旧习惯很难改掉。然后我像这样对信息进行了消毒:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name1"])) {
    $name1Err = " First Name is a required field.";
  } else {
      $name1 = test_input($_POST["name1"]);
    // check if name only contains letters and whitespace
      if (!preg_match("/^[a-zA-Z ]*$/",$name1)) {
      $name1Err = "Only letters and white space allowed";

of course test_input is another function that does a trim, strilashes, and htmlspecialchars. I think the input is pretty well sanitized. Not trying to be rude just showing what I did. When it came to the email I also checked to see if it was the proper format. I think the real answer is in the fact that some variables are local and some are global. I have got it working without errors for now so, while I'm extremely busy right now I'll accept shutting off errors as my answer. Don't worry I'll figure it out it's just not vitally important right now!

当然 test_input 是另一个执行修剪、条纹和 htmlspecialchars 的函数。我认为输入已经很好地消毒了。不要试图粗鲁,只是展示我所做的。当涉及到电子邮件时,我还检查了它是否格式正确。我认为真正的答案在于有些变量是局部变量,有些变量是全局变量。我现在已经让它正常工作了,所以虽然我现在非常忙,但我会接受关闭错误作为我的答案。别担心,我会弄清楚它现在并不是最重要的!

回答by sanjay mundhra

Assure you have used method="post" in the form you are sending data from.

确保您在发送数据的表单中使用了 method="post"。

回答by tony gil

apparently, the GET and/or the POST variable(s) do(es) not exist. simply test if "isset". (pseudocode):

显然,GET 和/或 POST 变量不存在。只需测试是否为“isset”。(伪代码):

if(isset($_GET['action'];)) {$action = $_GET['action'];} else { RECOVER FROM ERROR CODE }