Fall Semester 2002


Lecture Notes Thirteen: Introduction to PHP

Last week most everybody managed to install PHP4 as an Apache module.

We're also finished with

but we'll continue to use mysql.

We'll also frequently refer back to compare PHP with what we've done thus far.

Today we start PHP, and we use this set of notes as the start of an introduction to PHP.

As a reminder I include here my crontab file:

burrowww.cs.indiana.edu% crontab -l
0 8 * * * /u/dgerman/apache/apache_1.3.26/bin/apachectl graceful > /dev/null
burrowww.cs.indiana.edu%
One should do this when one is completely convinced the setup is perfect.

Otherwise we need to delete the accumulated e-mail on a daily basis.

PHP (What's in a name?)

PHP originally meant Personal Home Page.

Later following the GNU's recursive play on words (Gnu is Not Unix) the acronym changed.

So it now stands for PHP a Hypertext Processor.

Whatever it stands for, though, it will simplify your life somewhat.

Your PHP files will be placed under htdocs.

The simplest PHP file has no PHP inside per se.

burrowww.cs.indiana.edu% pwd
/nfs/paca/home/user1/dgerman/apache/apache_1.3.26/htdocs/weekSix
burrowww.cs.indiana.edu% ls -ld one*
-rw-r--r--   1 dgerman  faculty       120 Feb 14 12:07 one.php
burrowww.cs.indiana.edu% cat one.php
<html>
  <head><title>PHP Scripts</title></head>
  <body bgcolor=white>

  <h1> Hello, world! </h1> 

  </body>
</html>
burrowww.cs.indiana.edu%
We need to describe how this goes, but let's keep going for now.

PHP is a programming language, so it has variables, assignment statements, expressions, etc.

It will resemble Perl to a certain extent.

But let's see some (more) examples first.

Here's a second example.

Here's the source code:

<html>
  <head><title>PHP Scripts</title></head>
  <body bgcolor=white>

  <h1> Hello, world! </h1>

  <? $i 1?> 
  
  I have set <code>$i</code> to 1, but you can't see it. <p>

  Here's the value: <? echo $i?> <p>

  Hope you can see it now. <p>

  <? $i $i 1?> 

  Now <code>$i</code> is <?=$i?>. <p>

  </body>
</html>
(I placed it in two.php, since one.php already looks like this).

I don't even need to post the source code here.

Copy the file two.php into two.phps and access it.

Better yet, create a symbolic link from two.phps to two.php as follows:

ln -s two.php two.phps
PHP knows how to process both actual PHP code and PHP listing source code.

There are three different types of PHP tags, but we will use this one (<?, ?>) for now.

One important thing is that variables in HTML forms are easier to name.

For example, let's start from this form (call it orderForm.php):

<html><head><title>Bob's Auto Parts</title></head><body bgcolor="white">

<h1>Bob's Auto Parts</h1>

<h3> Order Form</h3>

<form action="processOrder.php" method="post">

<table border=0>

<tr bgcolor="#cccccc">
  <td width=150> Item </td>
  <td width=15>Quantity</td>
</tr>

<tr> 
  <td>Tires</td> 
  <td align=center><input type="text" name="tireqty" size=3 maxlength=3></td>
</tr>

<tr> 
  <td>Oil</td> 
  <td align=center><input type="text" name="oilqty" size=3 maxlength=3></td>
</tr>

<tr> 
  <td>Spark Plugs</td> 
  <td align=center><input type="text" name="sparkqty" size=3 maxlength=3></td>
</tr>

<tr> 
  <td colspan=2
      align=center><input type="submit" value="Submit Order"></td>
</tr>
</table>

</form>

</body>
</html>
Notice where it's sending the output.

(That could also be a CGI script, but we want to use PHP now).

As a matter of fact, can you describe the output (format and contents)?

Great!

Now the simplification.

First, we write this (call it processOrder.php):

<html><head><title>Order Results</title></head><body bgcolor="white">

<h1> Bob's Auto Parts</h1>

<h3>Order Results</h3>

<?
    echo "Thank you for your order!"; 
 ?>

</body>
</html>
Try it, if you want, on my server.

I hope that looks good to you.

Let's enhance processOrder.php a bit.

<html><head><title>Order Results</title></head><body bgcolor="white">

<h1> Bob's Auto Parts</h1>

<h3>Order Results</h3>

<?

    $tireqty += 0; 
    $oilqty += 0; 
    $sparkqty += 0; 

    echo $tireqty . " tires <br>" . 

         $oilqty . " bottles of oil <br>" . 

         $sparkqty . " spark plugs <p>" ; 

    if ($tireqty >= 0 && 
        $oilqty  >= 0 && 
        $sparkqty >= 0 && 
        ($tireqty + $oilqty + $sparkqty > 0) ) {
     
      echo "Thank you for your order!"; 

    } else {
  
      echo "This is not a valid order. "; 

    }
 ?>

</body>
</html>
As you see, one can get carried away, this way.

Please note the names of the variables and the names of the form elements.

Here's the source code for the new processOrder:

       <html><head><title>Order Results</title></head><body bgcolor="white">

       <h1> Bob's Auto Parts</h1>

       <h3>Order Results</h3>

       <?

           $tireqty 
+= 0
           
$oilqty += 0
           
$sparkqty += 0

           echo 
$tireqty " tires <br>" 

                
$oilqty " bottles of oil <br>" 

                
$sparkqty " spark plugs <p>" 

           if (
$tireqty >= && 
               
$oilqty  >= && 
               
$sparkqty >= && 
               (
$tireqty $oilqty $sparkqty 0) ) {
            
             echo 
"Thank you for your order!"

           } else {
         
             echo 
"This is not a valid order. "

           }
        
?>

       </body>
       </html>


The elements of %ENV are available by their short names, too:

<html><head><title>This is my portfolio</title></head><body bgcolor=white>

<? echo $QUERY_STRING ?> <p> 

<table width=100% cellpadding=2>

<tr> <td align=center> 

<? if ($QUERY_STRING == "seven") {

     echo "Lindley 07";

   } else {

     echo "<a href=\"$SCRIPT_NAME?seven\">Lindley 07</a>"; 

   }

 ?>
     </td> <td align=center> 

Lindley 08

     </td> <td align=center> 

Lindley 01

     </td> <td align=center> 

Lindley 09

     </td> 
</tr>
<tr> <td colspan=4 align=center>

  <? if ($QUERY_STRING == "seven") {
       echo 
            "<img src=\"http://www.cs.indiana.edu" . 
            "/dept/img/lh07.gif\">"; 
     } else {
       echo 
            "<img src=\"http://www.cs.indiana.edu" . 
            "/l/www/classes/a202-dger/sum99/a202.gif\">"; 
     }
  ?>

</td> 
</tr>
</table>

</table>

</body>
</html>
Here's the source code as rendered by PHP, for comparison:

       <html><head><title>This is my portfolio</title></head><body bgcolor=white>

       <? echo $QUERY_STRING ?> <p>

       <table width=100% cellpadding=2>

       <tr> <td align=center>

       <? if ($QUERY_STRING == "seven") {

            echo 
"Lindley 07";

          } else {

            echo 
"<a href=\"$SCRIPT_NAME?seven\">Lindley 07</a>"

          }

        
?>
            </td> <td align=center>

       Lindley 08

            </td> <td align=center>

       Lindley 01

            </td> <td align=center>

       Lindley 09

            </td>
       </tr>
       <tr> <td colspan=4 align=center>

         <? if ($QUERY_STRING == "seven") {
              echo 
                   
"<img src=\"http://www.cs.indiana.edu" 
                   
"/dept/img/lh07.gif\">"
            } else {
              echo 
                   
"<img src=\"http://www.cs.indiana.edu" 
                   
"/l/www/classes/a202-dger/sum99/a202.gif\">"
            }
         
?>

       </td>
       </tr>
       </table>

       </table>

       </body>
       </html>

What does this bring to mind?

The calculator likely becomes easier to write also:

<html><head><title>Bank Accounts</title></head><body bgcolor="white">

<? if ($fun == "add") {
     $acc += $arg; 
   } else if ($fun == "sub") {
     $acc -= $arg; 
   } else {

   }
 ?>

Current accumulator is: <? echo $acc ?>

<form method="post" action="<? echo $SCRIPT_NAME; ?>">

Amount: <input type="text" name="arg"> <p> 

Action: <select name="fun">
  <option value="non"> Click Me!
  <option value="add"> Deposit
  <option value="sub"> Withdraw
</select> <p> 

<input type="hidden" name="acc" value="<? echo $acc; ?>">

Fill in the form then push: <input type="submit" value="Proceed">

</form>

</body></html>
You will have seen the hidden field by now.

It helps us keep state on the client side.

PHP provides the ability to manage state on the server side.

Here's a typical script.

<? session_start();
   if (session_is_registered("acc")) { 
     if ($fun == "add") $acc += $arg; 
     else if ($fun == "sub") $acc -= $arg; 
   } else {
     $acc = 0; 
     session_register("acc"); 
   } 
 ?>

<html>
  <head>
    <title>Sessions Examples</title>
  </head>
  <body bgcolor=white>
    <form method="POST" action="<? echo $SCRIPT_NAME; ?>"> 

      The current value of the accumulator is: <? echo $acc ?> <p> 

      <table cellpadding=2>
        <tr> 
          <td> Amount: </td> 
          <td> <input type="text" name="arg" size=4> </td> 
          <td> Function: </td> 
          <td> <select name="fun"> 
                 <option value="non"> Click Me! 
                 <option value="add"> Deposit
                 <option value="sub"> Withdraw   
               </select> 
          </td> 
        </tr> 
      </table> 
       
      <p> Enter the amount, select a function, then press 
       
      <input type="submit" value="Proceed"> <p> 
       
    </form>
  </body>
</html>
The code in brown shows how values in the form fields can be retrieved. That's important, but not the central part of this example. Here's what gets created on /tmp if I work with this calculator a bit (which is what the example wants to bring forth):
burrowww.cs.indiana.edu% ls -ld /tmp/sess_05e56a5ed8be5e3a0ef771d9fb582df9
-rw-------   1 dgerman  faculty        10 Oct 17 14:44 /tmp/sess_05e56a5ed8be5e3a0ef771d9fb582df9
burrowww.cs.indiana.edu% cat /tmp/sess_05e56a5ed8be5e3a0ef771d9fb582df9
acc|i:122;burrowww.cs.indiana.edu% 
burrowww.cs.indiana.edu% 
My accumulator was 122 at the time I printed the file.

The name of the file contains the random session ID (in blue).

The contents of the file contains the server-side state (environment).

That is in red.

Note that for every browser that calls, a session ID is created.

The session ID is sent to the browser, and kept in a cookie, there.

(Other ways of storing the session ID on the browser are possible, too).

A file with the ownership of the server will then be created on the server.

Where will it be created?

Your config file (php.ini) determines that, and here's the line in it.

ifx.nullformat = 0

[Session]
; Handler used to store/retrieve data.
session.save_handler = files

; Argument passed to save_handler.  In the case of files, this is the path
; where data files are stored.
session.save_path = /tmp

; Whether to use cookies.
session.use_cookies = 1


; Name of the session (used as cookie name).
session.name = PHPSESSID

; Initialize session on request startup.
session.auto_start = 0

To summarize:

That's the basic idea behind sessions.

Next time we will cover:

At this point Homework Three should present no problem for you.


Last updated: Oct 7, 2002 by Adrian German for A348/A548