Adam
Adam

Reputation: 29079

how to properly handle php undefined index

I have a script where a user can input some text, view it, and change it. It looks like that:

if(isset($_POST['change']))
{
    $text = $_POST['text'];
    echo"
    <form method='post' action='datei.php'>
    <p>You wrote: $text</p>
    <input name='text' type='hidden' size='21' value='$text'>
    <input name='submit' type='submit' value='Change'>
    </form>";
}else
{
    $text = $_POST['text'];
    echo"
    <form method='post' action='datei.php'>
    <p>Write some additional Information</p>
    <input name='text' type='text' size='21' value='$text'>
    <input name='change' type='submit' value='View'>
    </form>";
 }

When I load the page the first time, I get the following notification

Notice: Undefined index: text in ...

I found two solutions how to fix the problem:

  1. Ignore Notifications
  2. Use isset()

If I would use isset I would have to change two lines from above to:

 if(isset($_POST['text']))$text = $_POST['text'];

and

<input name='text' type='text' size='21' value='"; if(isset($_POST['text'])) echo $text; echo"'>

Since my original form has more then 20 input fields, this would make the code less readable and more likly for erros when editing the code. Is there any better way to get around the notification that I currently miss?

Upvotes: 2

Views: 2521

Answers (1)

PatomaS
PatomaS

Reputation: 1603

First be sure that you define all the variables before using them, like

$text = false;

Plus, checking that a variable is set is always a good practice. Not to mention that you shouldn't be using $_POST directly.

Upvotes: 1

Related Questions