A simple PHP form example

PHP form FAQ: Can you share an example of a very simple PHP form (a self-processing PHP form)?

Still trying to catch up on a lot of PHP examples I've written but never published, here's the source code for a simple PHP form example. This form posts back to itself, and while I'm generally not a fan of that coding approach, I have used it from time to time for simple tasks.

A simple PHP form example

Here's the source code for this simple PHP form example:

// created by alvin alexander, http://devdaily.com
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];

<title>Simple PHP Form Example</title>


if (!isset($_POST['submit']))
  // display the form
  <form method="post" action="<?php echo $PHP_SELF;?>">
  First Name: <input type="text" name="first_name">
  <br/>Last Name: <input type="text" name="last_name">
  <br/><input type="submit" value="submit" name="submit">

  // display the output
  echo "<p>";
  echo "First Name: $first_name<br />";
  echo "Last Name: $last_name<br />";
  echo "</p>";


I just saved this PHP code to a file named testform.php on a test Apache PHP server, hit the URL, and everything seems to work as desired. Please note that I would never format HTML as shown here for anything other than a simple PHP example form like this.