Question

I am learning PHP. Here is the source code.

<?php
$text = $_POST['text'];

echo $text;
?>

<form action="index.php" method="post">
<input type="text" name="text" />
    <input type="submit">
</form>

Here is the result. I don't know where is the problem.

Notice: Undefined index: text in C:\xampp\htdocs\faisal\index.php on line 2

Was it helpful?

Solution

It means there's nothing in $_POST['text'] -- and there won't be, until after the form is submitted. You need to use isset() to check:

<?php
if(isset($_POST['text'])) {
    $text = $_POST['text'];

    echo $text;
}
?>

<form action="index.php" method="post">
<input type="text" name="text" />
    <input type="submit">
</form>

OTHER TIPS

When you first go to the page your special variable "$_POST" is empty, that is why you are getting an error. You need to check to see if anything is in there.

<?php
$text = '';
if(isset($_POST['text']))
{
  $text = $_POST['text'];
}

echo 'The value of text is: '. $text;
?>

<form action="index.php" method="post">
  <input type="text" name="text" />
  <input type="submit">
</form>

$_POST['text'] is only populated when the form is submitted. So when the page is first load it does not exist and you get that error. To compensate you need to check to see f the form is submitted before executing the rest of your PHP:

<?php
if ('POST' === $_SERVER['REQUEST_METHOD']) {
  $text = $_POST['text'];

  echo $text;
}
?>

<form action="index.php" method="post">
<input type="text" name="text" />
    <input type="submit">
</form>

You pprobably have to detemine if the form has been submitted or not.

<?php
if (isset($_POST['text'])) {
    $text = $_POST['text'];
    echo $text;
}
?>

<form action="index.php" method="post">
<input type="text" name="text" />
    <input type="submit">
</form>

Alternativly you can use $_SERVER['REQUEST_METHOD'].

if ($_SERVER['REQUEST_METHOD'] == 'POST') {...

We have to check whether user clicked on submit button or not, if yes then we have to set $test variable. If we will not use isset() method, we'll always get error.

<?php
if(isset($_POST['submit']))
{
  $text = $_POST['text'];
  echo $text;
}
?>

<form action="index.php" method="post">
<input type="text" name="text" />
    <input type="submit" name="submit" value="submit">
</form>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top