1

first of all this is my first post in stack <3 and of course sorry for my bad English. So i'm studying PHP and i have something like a problem in my mind:

when i write a code like:

if ($_POST['submit'])
{
    $total = $_POST["total"];
    $var = $_POST["var"];

function func($total, $var)
    {
     $lost = $total * $var / 100;
     $income = $total - $income;
     $result = "Income - " . $income . "<br />Lost - " . $lost;

     return $result;
    }

echo func($total, $var);
}
else
{
?>


<?php 
// HTML FORM : i write to number example total = 1000
// and var = 200 and result is 1000 - (1000/100*20)
?>
<form method="POST" action="index.php">
    <input type="text" name="total" />
    <input type="text" name="var" />

    <input type="submit" name="submit" value="Submit" />
</form>
<?php }?>

there is an error: Notice: Undefined index: submit when i search in google, i found a something like solution, error_reporting (E_ALL ^ E_NOTICE) but i think this is not a correct solution.

hakre
  • 193,403
  • 52
  • 435
  • 836
Mike
  • 55
  • 1
  • 7
  • Probably related question: http://stackoverflow.com/questions/6201230/workaround-for-validation-and-checking-if-the-form-has-been-actually-posted – zerkms Jun 24 '11 at 00:17
  • `Arr::get($array, $key, $default)` is very useful, try it – biakaveron Jun 24 '11 at 05:09

2 Answers2

2

I think its telling you that that $_POST['submit'] is not set ...

Try using this instead ..

if (array_key_exists('submit', $_POST)) {
Brian Patterson
  • 1,615
  • 2
  • 15
  • 31
  • Also, anywhere you are using the name attribute you should also have id ... so ... – Brian Patterson Jun 23 '11 at 23:56
  • Also, the accepted way of doing this, is using array_key_exists, (not empty or isset) because of certain vulnerabilities... – Brian Patterson Jun 24 '11 at 18:49
  • What vulnerabilities? I strongly perfer empty/isset personally -- it's less verbose, and also prevents an error in the case that the array itself is not set. – Frank Farmer Jun 25 '11 at 01:15
  • @Frank Farmer - If not set it will return FALSE, not an error as you suggest. (hence the IF() statement) Your goal in programming should be secure, functional code, not being less verbose. – Brian Patterson Jun 30 '11 at 17:52
  • If $myvar is uninitialized, `array_key_exists('submit', $myvar)` will raise a notice error, while `isset($myvar['submit'])` will not. Can you be specific about any "vulernabilities" or "insecurities" in using isset? – Frank Farmer Jun 30 '11 at 18:13
2

empty() and isset() are the tools you want in this situation

if (!empty($_POST['submit'])) {
Frank Farmer
  • 38,246
  • 12
  • 71
  • 89