[php] PHP error: Notice: Undefined index:

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:

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

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

This question is related to php variables indexing undefined

The answer is


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


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:

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!


Try this:

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

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

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


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

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.


undefined index means the array key is not set , do a var_dump($_POST);die(); before the line that throws the error and see that you're trying to get an array key that does not exist.


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

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_reporting set 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:

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

Make sure the tags correctly closed. And the closing tag will not include inside a loop. (if it contains in a looping structure).


I think there could be no form elements by name 'month' or 'op'. Can you verify if the HTML source (of the page which results in error when submitted) indeed has html elements by he above names


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

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

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.

Also, next time Google the error message first.


it just means that the array, $_POST in this case, doesn't have an element named what is undefined in your error. PHP issues a NOTICE instead of a WARNING of FATAL ERROR.

You can either log less events via editing php.ini or deal with it by first checking if the items is indeed initialized already by using isset()


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

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

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to variables

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes?

Examples related to indexing

numpy array TypeError: only integer scalar arrays can be converted to a scalar index How to print a specific row of a pandas DataFrame? What does 'index 0 is out of bounds for axis 0 with size 0' mean? How does String.Index work in Swift Pandas KeyError: value not in index Update row values where certain condition is met in pandas Pandas split DataFrame by column value Rebuild all indexes in a Database How are iloc and loc different? pandas loc vs. iloc vs. at vs. iat?

Examples related to undefined

Checking for Undefined In React Raw_Input() Is Not Defined How to resolve TypeError: Cannot convert undefined or null to object "undefined" function declared in another file? Passing Variable through JavaScript from one html page to another page Javascript - removing undefined fields from an object PHP How to fix Notice: Undefined variable: Undefined Symbols for architecture x86_64: Compiling problems Undefined or null for AngularJS PHP Notice: Undefined offset: 1 with array when reading data