Showing the Browser and IP Address

Here is a simple page that prints out the browser string and the IP address of the HTTP request. Create a file with the following content in your web directory, name it something like example.php3, and load it in your browser:
<html><head><title>PHP Example</title></head>
<body>
   You are using 
    <?php echo $_SERVER['HTTP_USER_AGENT'] ?>
   <br />
   and coming from 
    <?php echo $_SERVER['REMOTE_ADDR'] ?>
</body></html>
You should see something like the following in your browser window:
You are using Mozilla/5.0 (X11; U; Linux i686; en-US; 
rv:1.1b) Gecko/20020722
and coming from 127.0.0.1

1.13.2 Intelligent Form Handling

Here is a slightly more complex example. We are going to create an HTML form that asks the user to enter a name and select one or more interests from a selection box. We could do this in two files, where we separate the actual form from the data handling code, but instead, this example shows how it can be done in a single file:
<html><head><title>Form Example</title></head>
<body>
<h1>Form Example</h1>
<?
function show_form($first="", $last="", 
                   $interest="") {
 $options = array("Sports", "Business", "Travel", 
                  "Shopping", "Computers");
 if(!is_array($interest)) $interest = array( );
 ?>
 <form action="form.php" method="POST">
 First Name:
 <input type="text" name="first" 
        value="<?echo $first?>">
 <br />
 Last Name:
 <input type="text" name="last" 
        value="<?echo $last?>">
 <br />
 Interests:
 <select multiple name="interest[ ]">
 <?php
  foreach($options as $option) {
   echo "<option";
   if(in_array($option, $interest)) {
    echo " selected ";
   }
   echo "> $option</option>\n";
  }
 ?>
 </select><br />
 <input type=submit>
 </form>
<?php } // end of show_form( ) function

if($_SERVER['REQUEST_METHOD']!='POST') {
 show_form( );
} else {
 if(empty($_POST['first']) || 
    empty($_POST['last'])  ||
    empty($_POST['interest'])) {
  echo "<p>You did not fill in all the fields,";
  echo "please try again</p>\n";
  show_form($_POST['first'],$_POST['last'], 
            $_POST['interest']);
 }
 else {
  echo "<p>Thank you, $_POST[first] $_POST[last], you ";
  echo 'selected '. 
       join(' and ', $_POST['interest']);
  echo " as your interests.</p>\n";
 }
}
?>
</body></html>
There are a few things to study carefully in this example. First, we have isolated the display of the actual form to a PHP function called show_form(). This function is intelligent, in that it can take the default value for each of the form elements as an optional argument. If the user does not fill in all the form elements, we use this feature to redisplay the form with whatever values the user has already entered. This means the user only has to fill the fields he missed, which is much better than asking the user to hit the Back button or forcing him to reenter all the fields.