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 <? echo $HTTP_USER_AGENT ?><BR> and coming from <? echo $REMOTE_ADDR ?> </BODY></HTML>
You should see something like the following in your browser window:
You are using Mozilla/4.0 (compatible; MSIE 4.01; Windows 98) and coming from 207.164.141.23
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(empty($interest)) $interest=array(-1); ?> <FORM ACTION="form.php3" METHOD="POST"> First Name: <INPUT TYPE=text NAME=first VALUE="<?echo $first?>"> <BR> Last Name: <INPUT TYPE=text NAME=last VALUE="<?echo ...
Get PHP Pocket Reference 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.