Examples

The best way to understand the power of PHP is to examine some real examples of PHP in action, so we’ll look at some common uses of PHP in this section.

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

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 ...

Get PHP Pocket Reference, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.