5

Sorry if this is a rather basic question.

I have a page with an HTML form. The code looks like this:

<form action="submit.php" method="post">
  Example value: <input name="example" type="text" />
  Example value 2: <input name="example2" type="text" />
  <input type="submit" />
</form>

Then in my file submit.php, I have the following:

<?php
  $example = $_POST['example'];
  $example2 = $_POST['example2'];
  echo $example . " " . $example2;
?>

However, I want to eliminate the use of the external file. I want the $_POST variables on the same page. How would I do this?

Piccolo
  • 1,612
  • 4
  • 22
  • 38

1 Answers1

16

Put this on a php file:

<?php
  if (isset($_POST['submit'])) {
    $example = $_POST['example'];
    $example2 = $_POST['example2'];
    echo $example . " " . $example2;
  }
?>
<form action="" method="post">
  Example value: <input name="example" type="text" />
  Example value 2: <input name="example2" type="text" />
  <input name="submit" type="submit" />
</form>

It will execute the whole file as PHP. The first time you open it, $_POST['submit'] won't be set because the form has not been sent. Once you click on the submit button, it will print the information.

Piccolo
  • 1,612
  • 4
  • 22
  • 38
KaeruCT
  • 1,605
  • 14
  • 15
  • 1
    An even better solution would be to [leave the action attribute empty](http://stackoverflow.com/questions/9401521/is-action-really-required-on-forms) or [leave it out altogether if you're using HTML5](http://stackoverflow.com/questions/7048833/does-html5-require-an-action-attribute-for-forms). – thordarson Jan 30 '13 at 02:47
  • 2
    @thordarson Thanks for the heads-up! however, I've always preferred to put it just to be explicit. I think $_SERVER['PHP_SELF'] would've been better for this example. – KaeruCT Jan 30 '13 at 02:50