PHP Class Notes

Sometimes a textbook is too much, too many words, too much reading to find what you need. Sometimes online documentation isn't enough, too much detail, not enough perspective. These are class notes, filling the gap in between textbook and the documentation.

What is PHP?

PHP's Strengths

How PHP works

  1. Client requests a php page from a web server
  2. The web server, on receiving the request recognizes that the needed page is php based
  3. The web server passes the request along with any additional request information to the php server
  4. The php server locates the code for the requested page and executes the php statements located in that file and collects the output.
  5. The output is then returned to the web server as a standard html page, which is then sent to the client.

Writing PHP with PHP tags

<?PHP
  //PHP code goes here
?>
// PHP Short Tags
<?
  //PHP code goes here
?>
// PHP Script Tags
<script language="php">
  //php codes go here
</script>
// PHP with ASP style tags
<%
  //php codes go here
%>

PHP Statements

// Example PHP Document
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Welcome</title>
  </head>

  <body>
    <?php
      /*
        This dandy little script
        will welcome someone to php
      */

      //we are going to output something!!!
      echo "Welcome to PHP!!!";
      #All done outputting
    ?>
  </body>
</html>
// Simple Output with PHP
echo "<strong>Welcome to PHP!!!</strong><br/>";

Adding Dynamic Content

// Example of Dynamic Output
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Welcome</title>
  </head>
  <body>
    <?php
      echo "<strong>Welcome to PHP!!!</strong><br/>";
      echo "Today is " . date( 'l' ) . ", " . date( 'F' ) . " the " .date( 'dS, Y' ) . "<br/>";
      echo "The current time is " . date( 'g:i:s a' );
    ?>
  </body>
</html>

Calling Functions

String Concatenation

Using Variables

// PHP Document with Variables
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Welcome</title>
  </head>

  <body>
    <?php
      $first = "Hello";
      $second = ", ";
      $third = "World!";

      echo $first . $second . $third;
    ?>
  </body>
</html>

Assigning values to Variables

// Variables Example
$first = "Hello";
$second = ", ";
$third = "World!";

$fourth = $first . $second . $third;

echo $fourth;

Variables vs. Literals

// Duoble vs. Single Quotes
$first = "Hello";
$second = ", ";
$third = "World!";

$fourth = $first . $second . $third;

//change to single to see what happens
echo "I would like to say $fourth";

Data Types

// Casting
$totalamount = (float)$totalqty;
// Examples of Different type of data

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Data Types</title>
  </head>

  <body>
    <?php
      $name = "Victrola Firecracker";
      $id = 123456789;
      $age = 99.9;

      echo "Name value: " . $name . "<br/>";
      echo "Name type: " . getType( $name ) . "<br/>";
      echo "<hr/>";
      echo "ID value: " . $id . "<br/>";
      echo "ID type: " . getType( $id ) . "<br/>";
      echo "Is ID an integer? " . is_int( $id ) . "<br/>";
      echo "<hr/>";
      echo "Age value: " . $age . "<br/>";
      echo "Age type: " . getType( $age ) . "<br/>";
      echo "Is age real? " . is_real( $age ) . "<br/>";
    ?>
  </body>
</html>

Variable Status

Constants

define( ‘CONSTANT’, value );
<?php
  define( 'TOTALPOINTS', 800 );
  echo TOTALPOINTS;
?>

Variable Variables

<?php
  $id = "id123456789";

  //assign value
  $$id = "Victrola Firecracker";

  //see value
  echo $id123456789;
?>

Variable Scope

Passing Variables Between Pages

// Example URL for Requesting a page
<a href="receiver.php?fname=victrola">Send name</a>
// receiver.php
echo $_GET[ 'fname' ];
// updated url and receiver.php
<a href="receiver.php?fname=victrola&lname=firecracker">
  Send name
</a>

echo "First name received is " . $_GET[ 'fname' ] ."<br/>";
echo "Last name received is " . $_GET[ 'lname' ];
// receiver.php
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title></title>
  </head>

  <body>
   <form action="receiver.php" method="GET">
    <table>
      <tr>
        <td>First Name</td>
        <td>
          <input type="text" name="fname"/>
        </td>
      </tr>
      <tr>
        <td>Last Name</td>
        <td>
          <input type="text" name="lname"/>
        </td>
      </tr>
      <tr>
        <td colspan="2">
          <input type="submit"/>
        </td>
      </tr>
    </table>
   </form>
  </body>
</html>

Operators

Arithmetic operators

PHP’s Arithmetic Operators
Operator Name Example
+ Addition $a + $b
- Subtraction $a - $b or -$a
* Multiplication $a * $b
/ Division $a / $b
% Modulus $a % $b
// The basic calculation
<?php
  // approximate speed of light in miles per second
  $lightspeed = 186000;
  $days = 1000; // specify number of days here

  $seconds = $days * 24 * 60 * 60; // convert to seconds

  // compute distance
  $distance = $lightspeed * $seconds;

  echo "In " . $days;
  echo " days light will travel about ";
  echo $distance . " miles.";
?>
// get_input.php
<form action="lightcalc.php" method="post">
  Light travels at 186,000 miles per second in a vacuum. Enter a number of seconds in the field below to see how far light would travel in that amount of time.<br/><br/>

  <input type="text" name="seconds"/>
  <input type="submit" value="Calculate"/>
</form>
// lightcalc.php
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Light Calc</title>
    <?php
      $seconds = $_POST[ 'seconds' ];
      $lightspeed = 186000;
    ?>
  </head>

  <body>
    In

    <?php
       echo $seconds;
       echo ($seconds > 1 ? " seconds" : " second");
    ?>

    light would travel

    <?php
       $distance = $seconds * $lightspeed;
       echo $distance;
    ?>

    miles.
  </body>
</html>

String Operators

Assignment Operators

References

<?php
  $a = 9;
  $b = $a;
  $a = 10;
  echo "A: " . $a . "<br/>";
  echo "B: " . $b . "<br/>";
?>
<?php
  $first = 9;
  $second = &$first;
  $first = 10;
  echo "First: " . $first . "<br/>";
  echo "Second: " . $second . "<br/>";
  $second = 11;
  echo "First: " . $first . "<br/>";
  echo "Second: " . $second . "<br/>";
?>
PHP’s Combined Assignment Operators
Operator Use Equivalent to
+= $a += $b $a = $a + $b
-= $a -= $b $a = $a - $b
*= $a *= $b $a = $a * $b
/= $a /= $b $a = $a / $b
%= $a %= $b $a = $a % $b
.= $a .= $b $a = $a . $b

Pre and Post Increment and Decrement Operators

Equality Operator

Other Comparison Operators

PHP’s Comparison Operators
Operator Name
== Equals
=== Identical (equal and the same type)
!= Not Equal
!== Not Identical
<> Not Equal
< Less than
> Greater than
<= Less that or equal to
>= Greater than or equal to

Logical Operators

PHP’s Logical Operators
Operator Name
! NOT
&& AND
|| OR
And AND
Or OR

Other Operators

<?php
  $number =24;
  echo ($number>50 ? "That's a big number" : "Not so Big");
?>
$answer = @(9/0);

Execution Operator

<?php
  $output = `ls -l`;
  echo "<pre>" . $output . "</pre>";
?>

Precedence and Associativity

Implementing Control Structures

Making Decisions with Conditionals (Selection structures)

Do you agree to the terms of the license?
<form action="ifstatement2.php" method="POST">
  <input type="radio" name="agree" value="yes">
    YES
  </input>
  <input type="radio" name="agree" value="no">
    NO
  </input>
  <br/>
  <input type="submit" value="submit"/>
</form>
<?php
  if( $_POST[ 'agree' ] == 'yes' ) {
    echo "Thank you for agreeing";
  } else {
    echo "Sorry you wouldn't agree, maybe you should try another site.";
  }
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Change Colors</title>

    <?php
      $bgcolor = $_POST[ 'color' ];
      $fgcolor = "black";

      if( empty( $bgcolor ) ) {
        $bgcolor = "white";
      }

      if( $bgcolor == "black" || $bgcolor == "blue"
                      || $bgcolor == "green" ) {
       $fgcolor = "white";
      }
    ?>

    <style type="text/css">
      body {
       background-color: <?php echo $bgcolor; ?>;
       color: <?php echo $fgcolor; ?>;
      }
    </style>
  </head>

  <body>
    <form action="switchstatements.php" method="POST">
     Please choose a color:<br/>
      <select name="color">
        <option value="red"
          <?php if( $bgcolor == "red" )
                  echo 'selected="true"';
          ?>
        >Red</option>
        <option value="orange"
          <?php if( $bgcolor == "orange" )
                  echo 'selected="true"';
          ?>
        >Orange</option>
      <!-- do yellow, blue, green, purple, black also -->
      </select>
      <input type="submit" name="Change Color"/>
    </form>
  </body>
</html>
switch( $variable ) {
  case ‘a’:
    //do something;
    break;
case ‘b’ :
  //do something;
  break;
  default :
    //do something;
  }
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Select Shipping Method</title>
  </head>

  <body>
    <form action="SwitchExample1.php" method="POST">
      <?php
        $type = "";
        $cost = 0.00;

        if( $_POST[ 'shippingType' ] == "" ) {
          echo "Please Select a Shipping Method";
        } else {
          switch( $_POST[ 'shippingType' ] ) {
            case 'G':
              $type = "Get it when you get it";
              $cost = 1.23;
              break;
            case 'O':
              $type = "One Day Air";
              $cost = 12.34;
              break;
            case 'H':
              $type = "Half Day Air";
              $cost = 23.45;
              break;
            case 'I':
              $type = "Instantaneous";
              $cost = 34.56;
              break;
            default:
              echo "Don't know how you did it but that's
                  not an option";
              break;
          }
        }

        echo "You selected: " . $type . "<br/>";
        echo "The cost will be: $" . $cost . "<br/>";
      ?>
      <br/>
      <select name="shippingType">
        <option value="G">
          Get it when you get it - $1.23
        </option>
        <option value="O">
          One Day Air - $12.34
        </option>
        <option value="H">
          Half Day Air - $23.45
        </option>
        <option value="I">
          Instantaneous - $34.56
        </option>
      </select>
      <br/>
      <input type="submit" value="Select"/>
    </form>
  </body>
</html>

Repeating Actions through Iteration (Repetition Structures)

while( condition ) {
  //loop body
  }
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>While Loops</title>
  </head>

  <body>
    <?php
      $count = 0;

      while( $count < 50 ) {
        echo $count . " ";
        $count++;
      }
    ?>
  </body>
</html>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>While Loops</title>

    <style type="text/css">
      body {
        font-family: courier;
      }
    </style>

  </head>
  <body>
    <?php
      $row = 0;
      $column = 0;

      echo "&nbsp;&nbsp;&nbsp;&nbsp;";
      while( $row <= 10 ) {
        if( $row < 10 )
          echo $row . "&nbsp;&nbsp;";
        else
          echo $row , "&nbsp;";
        $row++;
      }

      echo "<br/>";
      echo "&nbsp;&nbsp;&nbsp;&nbsp;";
      $row = 0;

      while( $row <= 10 ) {
        echo "---";
        $row++;
      }

      $row = 0;
      echo "<br/>";

      while( $row <= 10 ) {
        if( $row < 10 )
          echo $row . "&nbsp;|&nbsp;";
        else
          echo $row . "|&nbsp;";

        while( $column <= 10 ) {
          $answer = $row * $column;

          $padding = "";

          if( $answer < 10 ) {
            $padding .= "&nbsp;";
          }

          if( $answer < 100 ) {
            $padding .= "&nbsp;";
          }

          echo $answer . $padding;
          $column++;
        }
        echo "<br/>";
        $row++;
        $column = 0;
      }
    ?>
  </body>
</html>
for( experssion1 ; condition ; experssion2 ) {
  //loop body
    }
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>For Loops</title>

    <style type="text/css">
      body {
        font-family: courier;
      }
    </style>

  </head>
  <body>
    <?php

      echo "&nbsp;&nbsp;&nbsp;&nbsp;";
      for( $row = 0 ; $row <= 10 ; $row++ ) {
        if( $row < 10 )
          echo $row . "&nbsp;&nbsp;";
        else
          echo $row , "&nbsp;";
      }

      echo "<br/>";
      echo "&nbsp;&nbsp;&nbsp;&nbsp;";

      for( $row = 0 ; $row <= 10 ; $row ++ ) {
        echo "---";
      }

      echo "<br/>";

      for( $row = 0 ; $row <= 10 ; $row++ ) {
        if( $row < 10 )
          echo $row . "&nbsp;|&nbsp;";
        else
          echo $row . "|&nbsp;";

        for( $column = 0 ; $column <= 10 ; $column++ ) {
          $answer = $row * $column;

          $padding = "";

          if( $answer < 10 ) {
            $padding .= "&nbsp;";
          }

          if( $answer < 100 ) {
            $padding .= "&nbsp;";
          }

          echo $answer . $padding;
        }
        echo "<br/>";
      }
    ?>
  </body>
</html>
do {
  //loop body
} while( condition );

Breaking out of a Control Structure or Script

Alternative Control Structure Syntax

Saving and Retrieving Data

Saving Data for Later

$fp = fopen( "path/file.ext", ‘mode’ );
Mode Mode Name Meaning
R Read Opens for reading starting at the beginning
R+ Read Opens for reading and writing starting at the beginning
W Write Opens for writing starting at the beginning, if the file exists, content is deleted, if it doesn’t exist, it will be created
W+ Write Opened for writing and reading, starts at the beginning, if the file exists, content is deleted, if it doesn’t exist, it will be created
X Cautious Write Open the file for writing, start at the beginning, if file exists it will NOT be opened
X+ Cautious Write Open the file for writing and reading, start at the beginning, if file exists it will NOT be opened
A Append Open the file for appending (writing only) If doesn’t exists, will be created
A+ Append Open the file for appending and reading, If doesn’t exists, will be created
B Binary Used with another mode to specify binary data being read or written (default mode)
T Text Used with other modes to specify reading or writing of text data
@$fp = fopen( "path/filename.ext", ‘ab’ );
if( !$fp ) {
  echo "Something went wrong";
  exit;
}

Opening files through HTTP or FTP

Writing to a file

fwrite( $fp, $outputvariable );
fwrite( resource handle, string string, [, length] )

Closing a file

fclose( $fp );
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Sign the Guest Book</title>
  </head>

  <body>
    <h2>Sign the Guest Book</h2>
    <form action="guestBookWrite.php" method="POST">
      <table>
        <tr>
          <td>Your Name:</td>
          <td>
            <input type="text" name="name"/>
          </td>
        </tr>
        <tr>
          <td>Your Email address:</td>
          <td>
            <input type="text" name="email"/>
          </td>
        </tr>
        <tr>
          <td colspan="2">
            Message:<br/>
            <textarea name="message" rows="10" cols="40">
            </textarea>
          </td>
        </tr>
      </table>
      <input type="submit" value="Sign the Guest Book"/>
    </form>
  </body>
</html>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Signed????</title>
  </head>

  <body>
    <?php
      $name = $_POST[ 'name' ];
      $email = $_POST[ 'email' ];
      $message = $_POST[ 'message' ];

      if( empty( $name ) || empty( $email )|| empty( $message ) ) {
        echo 'You did not complete the form.<br/>
            Please <a href="guestBookSign.php">
            try again</a></body></html>';
        exit;
      }

      $fp = fopen( "guestBook.txt", 'ab' );
      if( !$fp ) {
        echo "The guest book file could not be
              opened.</body></html>";
        exit;
      }

      $fileoutput = date( 'H:i m-d-Y' )
                  . "\t" . $name
                  . "\t" . $email
                  . "\t" . $message . "\n";

      fwrite( $fp, $fileoutput );

      echo 'The guestbook has been signed.<br/>
            <a href="">View the Guest Book</a>';

      fclose( $fp );
    ?>
  </body>
</html>

Reading from a file

fgets( resource fp, int length );
fgetss( resource fp, int length, string [allowable_tags] );
fgetcsv( resource fp, int length, [, string delimter [,
                      string enclosure] ] )
<?php
  @ $fp = fopen( "guestbook.txt", "r" );
    if( !$fp ) {
      echo "The guestbook file could not be
        opened.</body></html>";
      exit;
    }

?>

<table>
  <!--
    Simple read that puts entire
    line into a single row and cell
  -->
  <?php
    $line = fgets( $fp, 999 );

    while( !feof( $fp ) ) {
      echo "<tr><td>$line</td></tr>";
      $line = fgets( $fp, 999 );
    }

    fclose( $fp );
  ?>
</table>

Reading the Whole File

int readfile( string filename, [int include_use_path [, resource context ] ] )
boolean fpasstatementru( resource fp )
int file( string filename )

Reading Single Characters

char fgetc( resource fp )
<?php
  @ $fp = fopen( "guestbook.txt", "r" );
  if( !$fp ) {
    echo "The guestbook file could not be opened.</body></html>";
    exit;
  }
?>

<table>
  <tr>
    <th id="dateColumn">Date</th>
    <th>Name</th>
    <th>Email</th>
    <th>Comment</th>
  </tr>

<?php
  $field = "";
  $char = fgetc( $fp );

  echo "<tr>";

  while( !feof( $fp ) ) {
    if( $char == "\t" ) {
      echo "<td>$field</td>";
      $field = "";
    } elseif( $char == "\n" ) {
      echo "<td>$field</td>";
      $field = "";
      echo "</tr>\n<tr>";
    } else {
      $field .= $char;
    }

    $char = fgetc( $fp );
  }
?>

</table>
<a href="guestBookSign.php">Sign the Book Again</a>

Reading an Arbitrary Length

string fread( resource fp, int length )

Other Useful File Functions

boolean file_exists( string filename )
int filesize( string filename)
string n12br( string input )
boolean unlink( string filename )
rewind( resource fp )
int fseek( resource fp, int offset [, int whence] )
int ftell( resource fp )

Locking Files

boolean flock( resource fp, int operation [, int
                        &wouldblock ] )
Value of Operation Meaning
LOCK_SH (1) Reading lock. The file can be shared with other readers
LOCK_EX (2) Writing lock. The file is exclusive and cannot be shared.
LOCK_UN (3) The existing lock is released.
LOCK_NB (4) Blocking is prevented while trying to establish the lock.

Problems with Flat Files

Using Arrays

What is an Array?

Numerically Indexed Arrays

As of php5.4 you can now use [ ] interchangeable with array( )

Initializing Numerically Indexed Arrays

$names = array( ‘Jack’, ‘John’, ‘Fry’ );
      

or

$names = ['Jack','John','Fry'];
$people = $names;
$numbers = range( 1,100 );

$letters = range( ‘a’, ‘z’ );

Accessing Array Contents

echo $letters[ 20 ];
$names[ 2 ] = "Amy";

Using Loops to Access Arrays

for( $x = 0 ; $x < 3 ; $x++ ) {
  echo $names[ $x ] . "<br/>";
    }
foreach( $names as $current ) {
  echo $current . "<br/>";
}

Associative Arrays

Initializing the Array

$namesAndIDs = array( "John" => 102345, "Jack" => 102456,
                        "Amy"=> 102567 );

Accessing the Array Elements

echo "John’s ID: " . $namesAndIDs[ "John" ];

$namesAndIDs[ "Amy" ] = 103210;

Using Loops

foreach( $namesAndIDs as $key => $value ) {
  echo $key . " has a value of " . $value . "<br/>";
    }
while( $element = each( $namesAndIDs ) ) {
echo $element[ "key" ]; //could also be 0
echo " has a value of ";
  echo $element[ "value" ]; //could also be 1
  echo "<br/>";
    }
while( list( $name, $id ) = each( $namesAndIDs ) ) {
  echo $name . " has a value of " . $id . "<br/>";
    }
    <title>Simple Array Example</title>

    <?php
      $loginInfo = array( "John" => "pw",
                    "Jack" => "passwd",
                    "Amy" => "password" );

      $loginFailure = false;
    ?>

  <body>
    <?php
      if( ! empty( $_POST[ 'username' ] )
        && ! empty( $_POST[ 'password' ] ) ) {
        while( list( $uname, $pw ) = each( $loginInfo ) ) {
          if( $uname == $_POST[ 'username' ]
            && $pw == $_POST[ 'password' ] ) {
            echo "<h1>You are logged in</h1></body></html>";
            exit;
          } else {
            $loginFailure = true;
          }
        }
      }

      if( $loginFailure ) {
        echo "Your username and password are no good.";
      }
    ?>

    <h1>Please login...</h1>
    <form action="SimpleArrayExample.php" method="POST">
      <table>
        <tr>
          <td>Username:</td>
          <td>
            <input type="text" name="username"/>
          </td>
        </tr>
        <tr>
          <td>Password:</td>
          <td>
            <input type="password" name="password"/>
          </td>
        </tr>
      </table>
      <input type="submit" value="Login"/>
    </form>
  </body>
</html>

Array Operators

Operator Name Results
+ Union Right array is appended to left array, key clashes are not added
== Equality True is both array contain the same elements
=== Identity True if both arrays contain the same elements in the same order
!= Inequality True if the arrays do not contain the same elements
<> Inequality Same as !=
!== Non-identity True if both arrays do not contain the same elements in the same order

Multidimensional Arrays

$people = array (
                  array( "102345", "Jack", "Johnson" ),
                  array( "102456", "John", "Jackson" ),
                  array( "102567", "Amy", "Wong" )
               );

    

for( $row = 0 ; $row < 3 ; $row++ ) {

for( $column = 0 ; $column < 3 ; $column++ ) { echo $people[ $row ] [ $column ]; } echo "<br/>"; }

Sorting Arrays

Reordering Arrays

Loading Arrays from Files

<table>
<tr>
  <th id="dateColumn">Date</th>
    <th>Name</th>
    <th>Email</th>
    <th>Comment</th>
  </tr>

  <?php
    $info = fgetcsv( $fp, 999, "\t" );

    while( ! feof( $fp ) ) {
      echo "<tr>";
      for( $x = 0 ; $x < 4 ; $x++ ) {
        echo "<td>" . $info[ $x ] . "</td>";
      }
      echo "</tr>\n";
      $info = fgetcsv( $fp, 999, "\t" );
    }

    fclose( $fp );
  ?>
</table>
//The file function opens, reads, and then closes the file
$posts = file( "guestbook.txt" );

      

for( $x = 0 ; $x < count( $posts ) ; $x++ ) {

$line = explode( "\t", $posts[ $x ] ); echo "<tr>"; for( $field = 0 ; $field < count( $line ) ; $field++ ) { echo "<td>" . $line[ $field ] . "</td>"; } echo "</tr>\n"; }

Performing Other Array Manipulations

int array_push ( array &array, mixed value [, mixed ...] )
mixed array_pop ( array &array )

Functions for navigating arrays

array each ( array &array )
mixed current ( array &array )
mixed reset ( array &array )
mixed end ( array &array )
mixed next ( array &array )
mixed pos ( array &array )
mixed prev ( array &array )

Counting Elements in an Array

int count ( mixed var [, int mode] )
      

int sizeof ( mixed var [, int mode] )

array array_count_values ( array input )

Converting Arrays to Scalar Values

int extract(array var_array [, int extract_type [, string prefix]])
<body>
  <?php
    echo "Parameters passed to POST: " . count( $_POST ) .
                            "<br/><br/>";
    $fname = "";
    $lname = "";

    extract( $_POST, EXTR_IF_EXISTS );

    echo $lname . ", " , $fname . "<br/><br/>";
  ?>

  <form action="ExtractExample.php" method="POST">
    first name: <input type="text" name="fname"/><br/>
    last name: <input type="text" name="lname"/><br/>
    <input type="submit"/>
  </form>
</body>

String Manipulation and Regular Expressions

Formatting Strings

$s1 = "       this has leading whitespace";

$s1 = chop( $s1 );

echo "after chop: '" . $s1 . "'" . "<br/>";

$s1 = rtrim( $s1 );

echo "after rtrim: '" . $s1 . "'" . "<br/>";

$s1 = ltrim( $s1 );

echo "after ltrim: '" . $s1 . "'" . "<br/>";

$s2 = "This has trailing whitespace       ";

$s2 = chop( $s2 );

echo "after chop: '" . $s2 . "'" . "<br/>";

Formatting Strings for Presentation

$longLine = "Is this a dagger I see before me\n handle toward my
          hand?\nCome, let me clutch thee!";

$formattedLine = nl2br( $longLine );

echo $longLine;
echo "<hr/>";
echo $formattedLine;
void printf( string format [, mixed args…] )
string printf( string format [, mixed args…] )
%[ ‘padding_character ] [ - ] [ width ] [ .precision ] type
Type Meaning
b Integer printed as a binary
c Integer printed as a character
d Integer as a decimal
f Double as a floating point
o Integer as an octal
s String as a string
u Integer as unsigned decimal
x (lower) Integer as a hexadecimal with lowercase letters
X (upper) Integer as a hexadecimal with upper case letters
$num = 123.456789;

echo "the number is $num<br/>";
      

printf( "the number is %s <br/>", $num );

$output = sprintf( "the number is %s <br/>", $num ); echo $output; $othernum = 789.432;

printf( "two numbers are %s and %s<br/>", $num, $othernum );

printf( "the number with 2 decimal places is %.2f <br/>", $num );

printf( "the number in hex %x <br/>", $num );

printf( "the number in octal %o<br/>", $num );

printf( "the number in binary %b <br/>", $num );

Changing Case

Function Description
strtoupper( ) Converts all characters in the string into uppercase
strtolower( ) Converts all characters in the string into lowercase
ucfirst( ) Capitalizes the first letter of the string
ucwords( ) Capitalizes the first letter of every word in the string

Joining and Splitting String

array explode( string seperator, string input [ , int limit ] )
<?php
  $tlds = array( "com", "org", "edu", "gov", "mil", "net" );
?>
<body>
  <?php
    if( isset( $_POST[ 'email' ] ) ) {
      $email = $_POST[ 'email' ];

      $parts = explode( "@", $email );

      if( count( $parts ) != 2 ) {
        echo "The email address contain to me @ signs<br/>";
      }

      echo "Email name: " . $parts[ 0 ] . "<br/>";
      echo "Full Domain name: " . $parts[ 1 ] . "<br/>";

      $domainParts = explode( ".", $parts[ 1 ] );

      $match = false;
      foreach( $tlds as $tld ) {
        if( $domainParts[ 1 ] == $tld ) {
          $match = true;
        }
      }

      if( ! $match ) {
        echo "The TLD for your domain appears invalid.<br/>";
      }

      echo "Domain Identifier: " . $domainParts[ 0 ] . "<br/>";
      echo "TLD: " . $domainParts[ 1 ] . "<br/>";

      $newEmail = implode( "@", $parts );

      echo "The reconstituted email address is: " . $newEmail .
                              "<br/>";
    }
  ?>

  <form action="splittingAndJoining.php" method="POST">
    Email Address: <input type="text" name="email"/>
    <input type="submit" value="Check Email"/>
  </form>
</body>

String Tokenizing

string strtok( string input, string seperator )
$email = "victrola@firecracker.org";

$token = strtok( $email, "@." );

echo $token . "<br/>";

    

while( $token != '' ) {

$token = strtok( "@." ); echo $token . "<br/>"; }

Substrings

String substr( string string, int start [ , length ] )

Comparing Strings

int strcmp( string str1, string str2 )
$s1 = "4";
$s2 = "100";

$return = strcmp( $s1, $s2 );

echo "4 comes after 100: ";
if( $return > 0 ) {
echo "true<br/>";
} else {
  echo "false<br/>";
}

$return = strnatcmp( $s1, $s2 );

echo "4 comes after 100: ";
if( $return > 0 ) {
echo "true<br/>";
} else {
  echo "false<br/>";
}

String Lengths

Matching and Replacing Substring

string strstr( string haystack, string needle )

Finding the Position of a Substring

int strpos( string haystack, string needle, int [, offset ] )

Replacing Substrings

mixed str_replace( mixed needle, mixed new_needle, mixed haystack
                            [, &count ] )

$badwords = array( "microsoft", "windows", "office" );
$message = str_replace( $badwords, '@#$%&*', $message );
string substr_replace( string string, string replacement,
                  int start, int [length] )

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
    <title>Signed????</title>
  </head>

  <body>
    <?php
      $name = $_POST[ 'name' ];
      $email = $_POST[ 'email' ];
      $message = $_POST[ 'message' ];

      if( empty($name) || empty($email) || empty($message) ) {
        echo 'You did not complete the form.<br/>Please
            <a href="guestBookSign.php">try again</a>
                  </body></html>';
        exit;
      }

      $fp = fopen( "guestBook.txt", 'ab' );
      if( !$fp ) {
    echo "The guest book file could not be
          opened.</body></html>";
        exit;
      }

      $message = nl2br( trim($message) );

      $message = str_replace( "\n", "", $message );

      $fileoutput = date( 'H:i m-d-Y' )
                . "\t"
                . $name
                . "\t"
                . $email
                . "\t"
                . $message
                . "\n";

      fwrite( $fp, $fileoutput );

      echo 'The guestbook has been signed.<br/>
        <a href="guestBookView2.php">View the Guest Book</a>';

      fclose( $fp );
    ?>
  </body>
</html>

Regular Expressions

The Basics

[ cbh ]at
[ a-zA-Z ]at
[ ^cbh ]at
Class Matches
[[ :alnum: ]] Alphanumeric characters
[[:alpha:]] Alphabetic characters
[[:lower:]] Lowercase letters
[[:upper:]] Uppercase letters
[[:digit:]] Decimal digits
[[:xdigit:]] Hex digits
[[:punct:]] Punctuation
[[:blank:]] Tabs and spaces
[[:space:]] Whitespace characters
[[:cntrl:]] Control characters
[[:print:]] All printable characters
[[:graph:]] All printable characters except for space
(vary ){3}
(very ){2,4}
(very ){2, }
(end|net|gov)
int preg_match( string pattern, string search, array [matches ] )
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Get Links</title>
  </head>

  <body>
    <?php
      if( ! empty( $_POST[ 'url' ] ) ) {
        if( ! eregi( '<a href="http://livepage.apple.com/">http://www\.[a-z0-9_\-\.]+\.[a-zA-Z]+</a>', $_POST[ 'url' ], $good ) ) {
          echo "That does not appear to be a valid URL.<br/>";
        }

        echo "<h1>Links for URL " . $_POST[ 'url' ] . "</h1>";

        @ $fp = fopen( $_POST[ 'url' ], r );
        if( !$fp ) {
          echo "That url could not be opened.</body></html>";
          exit;
        }

        $line = fgets( $fp );

        while( ! feof( $fp ) ) {
          //eregi( '<a href="http://livepage.apple.com/">http://www\.[a-z0-9_\-\.]+\.[a-zA-Z]+</a>', $line, $matches );
          eregi( '<a href="http://livepage.apple.com/">http://www\.([a-z0-9_\-</a>\.]+)\.(com|net|org|info)', $line, $matches );

          if( !empty( $matches[ 0 ] ) ) {
            echo $matches[ 0 ] . "<br/>";
          }

          $matches = array( );
          $line = fgets( $fp );
        }

        fclose( $fp );
      }
    ?>

    <form action="getLinks.php" method="POST">
      URL to Search for Links:
      <input type="text" name="url"/>
      <br/>
      <input type="submit" value="Search"/>
    </form>
  </body>
</html>
string preg_replace( string pattern, string replacement, string search )

$email = preg_replace( '@', ' at ', $email );
$email = preg_replace( '\.', ' dot ', $email );
array preg_split( string pattern, string search [, int max] )

Functions and Reusing Code

Reusing code

Using require( ) and include( )

Using require( ) for Website Templates

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>The Sample Company</title>

    <style type="text/css">
      body {
        font-family: arial;
        margin: 0px;
      }

      #banner {
        background-color: #fc0;
        height: 60px;
        border-bottom: 1px solid black;
      }

      #banner img {
        margin: 5px;
      }

      #banner #nav {
        float: right;
        width: 300px;
      }

      #banner #nav ul {
        padding: 0px;
        margin: 5px;
        list-style: none;
      }

      #banner #nav ul li {
        float: right;
        width: 88px;
        border: 1px solid black;
        margin: -1px 0px 0px -1px;
        text-align: center;
      }

      #banner #nav ul li a {
        display: block;
        text-decoration: none;
        color: white;
        padding: 3px;
      }

      #banner #nav ul li a:hover {
        background-color: #ff9;
        color: black;
      }

      #footer {
        background-color: #fc0;
        padding: 5px;
        border-top: 1px solid black;
        border-bottom: 3px solid black;
        font-size: .5em;
      }

      #content {
        margin: 10px;
      }
    </style>

  </head>

  <body>
    <div id="banner">
      <img alt="The Sample Company" src="images/banner.gif"/>
      <div id="nav">
        <ul>
          <li><a href="#">Home</a></li>
          <li><a href="#">Contact</a></li>
          <li><a href="#">Downloads</a></li>
          <li><a href="#">Products</a></li>
          <li><a href="#">About</a></li>
          <li><a href="#">Legal</a></li>
        </ul>
      </div>
    </div>
    <div id="content">
    Pages Content
    </div>
    <div id="footer">
      &copy; Copyright 2005 The Sample Company
    </div>
  </body>
</html>
<?php require( 'includes/header.inc' ); ?>

      

This is the home page

<?php require( 'includes/footer.inc' ); ?>
</div>

    <div id="footer">
      &copy; Copyright
        <?php echo date( 'Y' ); ?> The Sample Company
      <span id="date"><?php echo date( 'l, F jS Y' ); ?></span>
    </div>
  </body>
</html>

The include( ) Construct

Using require_once( ) and include_once( )

Using auto_prepend_file( ) and auto_append_file( )

php_value auto_prepend_file "includes/header.inc"
      

php_value auto_append_file "includes/footer.inc"

Using Functions in PHP

Function Structure

<?php
    

function say_hello( ) {

echo "Hello"; } ?>
<?php function say_hello( ) { ?>
  Hello
<?php } ?>

Using Parameters and Returning Values

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Functions Test</title>

    <?php
      function validate( $name ) {
        if( isset( $_POST[ $name ] ) ) {
          $data = trim( $_POST[ $name ] );

          if( eregi( '^[a-z]+$', $data ) ) {
            return true;
          } else {
            return false;
          }
        }
      }
    ?>

  </head>

  <body>
    <?php
      $fnamevalid = validate( 'fname' );

      if( ! $fnamevalid ) {
        echo "The name is not correct<br/>";
      }
    ?>
    <h1>Please Complete the Form</h1>
    <form action="TestFunctions.php" method="post">
      <table>
        <tr>
          <td>First Name:</td>
          <td>
            <input type="text" name="fname"/>
          </td>
        </tr>
      </table>
      <input type="submit" value="Done"/>
    </form>
  </body>
</html>
<?php
  function validate( $type, $name ) {
    if( isset( $_POST[ $name ] ) ) {
      $data = trim( $_POST[ $name ] );

      if( $type == 'name' ) {
        if( eregi( '^[a-z]+$', $data ) ) {
          return true;
        } else {
          return false;
        }
      } else if( $type == 'phone' ) {
        if( eregi( '^[0-9]{3}\-[0-9]{3}\-[0-9]{4}$', $data ) ) {
          return true;
        } else {
          return false;
        }
      }
    }
  }
?>

<?php
  $fnamevalid = validate( 'name', 'fname' );
  $lnamevalid = validate( 'name', 'lname' );
  $phonevalid = validate( 'phone', 'phone' );

  if( ! $fnamevalid ) {
    echo "The first name is not correct<br/>";
  }

  if( ! $lnamevalid ) {
    echo "The last name is not correct<br/>";
  }

  if( ! $phonevalid ) {
    echo "The phone number is not correct ( try 999-999-9999 )<br/>";
  }
?>
<?php
  function validate( $type, $name, $displayerrors = false ) {
    if( isset( $_POST[ $name ] ) ) {
      $data = trim( $_POST[ $name ] );

      if( $type == "name" ) {
        $regex = ‘^[a-z]+$’;
      } else if( $type == "phonenumber" ) {
        $regex = ‘^[0-9]{3}\-[0-9]{3}\-[0-9]{4}$’;
      }

      if( eregi( $regex, $data ) ) {
        return true;
      } else {
        if( $displayerrors )
          echo ‘"’ . $data . ‘"’ . " is not a valid " . $type .
                              "<br/>";
        return false;
      }
    }
  }
?>

<?php
  $fnamevalid = validate( ‘name’, ‘fname’, true );
  $lnamevalid = validate( ‘name’, ‘lname’, true );
  $phonevalid = validate( ‘phonenumber’, ‘phone’, true );
?>

Dealing with Scope

Passing by Reference Versus Passing by Value

Object Oriented Programming

OOP Concepts

Creating Classes, Attributes, and Operations

class Box {
  var $width;
var $height;

function draw( ) {
    echo $box;
  }
      }
function __construct( $w = 100, $h = 100 ) { }

Instantiating Classes (creating objects)

$b1 = new Box( );
$b2 = new Box( 200, 300 );

Accessing Class Attributes and Methods

function __construct( $w = 100, $h = 100 ) {
$this->width = $w;
  $this->height = $h;
    }
function draw( ) {
$box = '<div style="border: 1px solid black; width: ' . $this->width . 'px; height: ' . $this->height . 'px;">&nbsp;</div>';
  echo $box;
    }

$b1->width = 200;
$b1->height = 200;
$b1->draw( );
$b2->draw( );
public function setwidth( $value ) {
if( is_integer( $value ) ) {
  $this->width = $value;
  }
      }

    

public function setheight( $value ) {

if( is_integer( $value ) ) { $this->height = $value; } }
$b1->color = "red";
echo $b1->color;
<?php
  class Box2 {
    public $attribs = array( );
    public function __construct( $w = 100, $h = 100 ) {
      $this->attribs[ 'width' ] = $w . "px";
      $this->attribs[ 'height' ] = $h . "px";
    }

    public function __set( $name, $value ) {
      switch( $name ) {
        case 'width':
        case 'height':
          if( is_integer( $value ) ) {
            $this->attribs[ $name ] = $value . "px";
          }
          break;
        default:
          $this->attribs[ $name ] = $value;
      }
    }

    public function __get( $name ) {
      return $this->attribs[ $name ];
    }

    public function draw( ) {
      $box = '<div style="';
      while( $element = each( $this->attribs ) )
      {
        $element[ 0 ] = eregi_replace( '_', '-', $element[ 0 ] );
        $box .= $element[ 0 ] . ": " . $element[ 1 ] . "; ";
      }
      $box .= '">&nbsp;</div>';
      echo $box;
    }
  }
?>
$b3 = new Box2( 200, 400 );
$b3->width = "bob";
$b3->draw( );

Implementing Inheritance

<?php
  require_once( 'Box2.php' );

  class FilledBox extends Box2 {
    protected $bgcolor;

    function __construct( $w = 100, $h = 100, $bgc = "black" ) {
      parent::__construct( $w, $h );
      $this->bgcolor = $bgc;
    }

    public function draw( ) {
      $box = '<div style="background-color: ' . $this->bgcolor .
            '; border: 1px solid ' . $this->bgcolor . '; width:
            ' . $this->attribs[ 'width' ] . 'px; height: ' .
            $this->attribs[ 'height' ] . 'px;">&nbsp;</div>';
      echo $box;
    }
  }
?>
<?php
  interface Displayable {
    function display( );
  }
?>

        

require_once( "displayable.php" );

class FilledBox extends Box2 implements Displayable { …

public function display( ) {

$this->draw( ); }

class Math {
  Const PI = 3.14159;
    }
echo Math::PI;
$b2 = clone $b1
public function __call( $method, $args ) {
if( count( $args ) == 2 )
  call2argmethod( );
  else if( count( $args ) == 3 )
    call3argmethod( );
    }
function __autoload( $classname ) {
  require_once( "../includes/" . $classname . ".php" );
    }
$b1 = new Box( 200, 300 );
$b1->setwidth( 500 );
$b1->color = "red";
echo $b1->color;
$b1->draw( );

      

foreach( $b1 as $attrib ) {

echo $attrib . "<br/>"; }
<?php
  require_once( 'ObjectIterator.php' );

  //class Box2 implements IteratorAggregate interface
  class Box2 implements IteratorAggregate {
    public $attribs = array( );

    public function __construct( $w = 100, $h = 100 ) {
      $this->attribs[ 'width' ] = $w . "px";
      $this->attribs[ 'height' ] = $h . "px";
    }

    public function __set( $name, $value ) {
      switch( $name ) {
        case 'width':
        case 'height':
          if( is_integer( $value ) ) {
            $this->attribs[ $name ] = $value . "px";
          }
          break;
        default:
          $this->attribs[ $name ] = $value;
      }
    }

    public function __get( $name ) {
      return $this->attribs[ $name ];
    }

    public function draw( ) {
      $box = '<div style="';
      while( $element = each( $this->attribs ) )
      {
        $element[ 0 ] = eregi_replace( '_', '-', $element[ 0 ] );
        $box .= $element[ 0 ] . ": " . $element[ 1 ] . "; ";
      }
      $box .= '">&nbsp;</div>';
      echo $box;
    }

    //class is able to return a custom iterator object
    public function getIterator( ) {
      return new ObjectIterator( $this );
    }
  }
?>

<!—the iterator object for Box2 -->
<?php
  class ObjectIterator implements Iterator {
    private $obj;
    private $count;
    private $currrentIndex;

    function __construct( $obj ) {
      $this->obj = $obj;
      $this->count = count( $this->obj->attribs );
    }

    function rewind( ) {
      $this->currentIndex = 0;
      reset( $this->obj->attribs );
    }

    function valid( ) {
      return $this->currentIndex < $this->count;
    }

    function key( ) {
      return key( $this->obj->attribs );
    }

    function current( ) {
      return $this->obj->attribs[ $this->key( ) ];
    }

    function next( ) {
      $this->currentIndex++;
      next( $this->obj->attribs );
    }
  }
?>

//Box2 being iterated with a custom iterator
$i = $b3->getIterator( );
                                    

for( $i->rewind( ) ; $i->valid( ) ; $i->next( ) ) {

$key = $i->key( ); $value = $i->current( ); echo "$key => $value<br/>"; }
private function buildCode( ) {
  $box = '<div style="';
  while( $element = each( $this->attribs ) )
  {
    $element[ 0 ] = eregi_replace( '_', '-', $element[ 0 ] );
    $box .= $element[ 0 ] . ": " . $element[ 1 ] . "; ";
}
$box .= '">&nbsp;</div>';

  return $box;
    }

        

public function draw( ) {

echo $this->buildCode( ); }

public function __toString( ) {

return $this->buildCode( ); }

Taking it to the Next Level

<?php
  //
  // Code for a standard page on the Sample Company's website
  //

  class TSCPage {
    private $content;
    private $filename;
    private $path;
    private $title;
    private $links = array( );

    public function __construct( ) {
      $this->filename = basename( $_SERVER["PHP_SELF"] );
      $this->path = dirname( $_SERVER["PHP_SELF"] );
      $this->title = $this->filename;
    }

    public function setContent( $c ) {
      $this->content = $c;
    }

    public function addContent( $nc ) {
      $this->content .= $nc;
    }

    public function setTitle( $t ) {
      $this->title = $t;
    }

    public function addLink( $title, $href ) {
      $this->links[ $title ] = $href;
    }

    public function displayLinks( ) {
      foreach( $this->links as $title => $href ) {
        if( basename( $href ) == $this->filename ) {
          echo "<li><a id=\"current\">$title</a></li>";
        } else {
          echo "<li><a href=\"$href\">$title</a></li>";
        }

      }
    }

    public function display( ) {
      ?>

      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

      <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
        <head>
          <title>
            The Sample Company –
              <?php echo $this->title ?>
          </title>

          <link type="text/css" rel="stylesheet" href="../stylesheets/errors.css"/>
          <link type="text/css" rel="stylesheet" href="../stylesheets/tables.css"/>
          <link type="text/css" rel="stylesheet" href="../stylesheets/general.css"/>
          <link type="text/css" rel="stylesheet" href="../stylesheets/FloatingBoxes.css"/>
          <?php
            if( isset( $pagetype ) && $pagetype == "admin" ) {
              echo '<link type="text/css" rel="stylesheet"
                  href="../stylesheets/admincolors.css"/>';
            } else {
              echo '<link type="text/css" rel="stylesheet"
                  href="../stylesheets/sitecolors.css"/>';
            }
          ?>

        </head>

        <body>
          <div id="banner">
            <img alt="The Sample Company"
                src="../images/TSCLogo.gif"/>
            <h1>The Sample Company</h1>
            <div id="nav">
              <ul>
                <?php $this->displayLinks( ); ?>
              </ul>
            </div>
          </div>

          <div id="content">

      <?php

      echo $this->content;

      ?>

          </div>

          <div id="footer">
            &copy; Copyright
            <?php echo date( 'Y' ); ?> The Sample Company
            <span id="date">
              <?php echo date( 'l, F jS Y' ); ?>
            </span>
          </div>
        </body>
      </html>

      <?php
    }
  }
?>

<?php
  function __autoload( $classname ) {
    require_once( "../includes/" . $classname . ".php" );
  }

  $home = new TSCPage( );

  $home->setTitle( "Home" );

  $home->addLink( "Home", "index.php" );
  $home->addLink( "Contact", "contact.php" );
  $home->addLink( "Guest Book", "guestbookview.php" );
  $home->addLink( "Products", "products.php" );
  $home->addLink( "About", "about.php" );
  $home->addLink( "FAQ's", "faqs.php" );

  $home->setContent( "

  <h1>Welcome to the Homepage of The Sample Company</h1>
  <p>
    Lorem ipsum …
  </p>
  <p>
    Donec erat. Nunc …
  </p>
  <p>
    Morbi in justo. In …
  </p>
  <p>
    Donec erat. Nunc …
  </p>

  ");
  $home->addContent( "This is the content" );
  $home->addContent( "<br/>This is new content" );

  $home->display( );
?>

Exception Handling

Concepts

throw new Exception( ‘message’, code );

<?php
  //assume these values come from a form
  $x = 9;
  $y = 0;

  try {
    if( $y != 0 ) {
      echo $x / $y;
    } else {
      throw new Exception( 'Cannot divide by Zero', 999 );
    }
  } catch( Exception $e ) {
    echo "<h2>An error occured</h2>";
    echo "The error was on line " . $e->getLine( )
        . " in the file called " . $e->getFile( ) . "<br/>";
    echo "The error is: " . $e->getMessage( )
        . " (" . $e->getCode( ) . ")<br/>";
  }
    ?>

The Exception Class

<?php
  $x = 9;
  $y = 0;

  try {
    divide( $x, $y );
  } catch( Exception $e ) {
    echo "An error occured<br/>";
    echo "<em>" . $e->getTraceAsString( ) . "</em>";
  }

  function divide( $n, $d ) {
    if( $d == 0 ) {
      throw new Exception( 'Cannot divide by zero', 999 );
    } else {
      echo $n / $d;
    }
  }
?>

User Defined Exceptions

<?php
  class ArithmeticException extends Exception {
    function __toString( ) {
      $output = "<h2>Arithmetic Exception</h2>";
      $output .= "<strong>" . $this->getMessage( )
            . "</strong> was the problem found on line <strong>"
            . $this->getLine( ) . "</strong>";
      $output .= " of the file, <strong>"
            . $this->getFile( ) . "</strong><br/><br/>";
      $output .= '<div style="border-bottom: 1px solid
                black">Back Trace</div>';
      $output .= "<em>" . $this->getTraceAsString( ) . "</em>";

      return $output;
    }
  }
?>

<?php
  $x = 3;
  $y = 10;

  try {
    divide( $x, $y );
  } catch( ArithmeticException $ae ) {
    echo $ae;
  } catch( Exception $e ) {
    echo "An error occured - " . $e->getMessage( ) . "<br/>";
    echo "<em>" . $e->getTraceAsString( ) . "</em>";
  }

  function divide( $n, $d ) {
    if( $d == 0 ) {
     throw new ArithmeticException('Cannot divide by zero',999 );
    } else if( $n == 9 ) {
      throw new Exception( "I don't like the number nine", 8 );
    } else {
      echo $n / $d;
    }
  }
?>

Relational Databases and SQL

Organizing Data in Databases

Characters --> fields --> records --> tables --> database

Defining Field Data Types and Table Structures

Keys

Relationships

  Classes
    Class ID
    Description
  Students
    Student ID
    First name
    Last name
    Middle initial
    Phone number
    Address
  Instructors
    Instructor ID
    First name
    Last name
    Middle initial
    Office Phone
    Home Phone
    Home Address
    Department
  Books
    ISBN
    Title
    Author(s)
    Subject/Category
    Price
  Customers
    Customer ID (login name)
    Password
    Address
    City
    State
    Zip
    Phone
  Employees
    Employee ID (login name)
    Password
    Security Level
  Orders
    orderNumber
    date
    customerID
  OrderItems
    orderNumber
    ISBN

Database Management Systems and SQL

Creating Tables with SQL

CREATE TABLE tablename (
  Fieldname1 datatype1 [(size1)] [PRIMARY KEY ],
  Fieldname2 datatype2 [(size2)] [PRIMARY KEY ],
  …
      

);

CREATE TABLE books (

ISBN varchar(15) PRIMARY KEY, Title varchar( 100 ) NOT NULL, Author varchar( 50 ) NOT NULL, Category varchar( 30 ), Price float

);

CREATE TABLE customers (

customerID varchar( 30 ) NOT NULL, password varchar( 30 ) NOT NULL, firstName varchar( 15 ) NOT NULL, lastName varchar( 15 ) NOT NULL, address varchar( 30 ), city varchar( 15 ), state char( 2 ), zip varchar( 10 ), phone varchar( 10 ), PRIMARY KEY (customerID)

);

CREATE TABLE employees (

employeeID varchar( 30 ) NOT NULL, password varchar( 30 ) NOT NULL, firstName varchar( 15 ) NOT NULL, lastName varchar( 15 ) NOT NULL, securityLevel int( 1 ) NOT NULL, PRIMARY KEY (employeeID)

);

CREATE TABLE orders (

orderNumber int( 11 ) AUTO_INCREMENT NOT NULL PRIMARY            

                                                       KEY,

customerID varchar( 30 ) NOT NULL, date date NOT NULL, FOREIGN KEY (customerID) REFERENCES

                                      customers(customerID)

);

CREATE TABLE orderItems (

ISBN varchar( 15 ) NOT NULL, orderNumber int( 11 ) NOT NULL, PRIMARY KEY (ISBN,orderNumber), FOREIGN KEY (ISBN) REFERENCES books(ISBN), FOREIGN KEY (orderNumber) REFERENCES orders(orderNumber) );

Inserting Data with SQL

INSERT INTO tablename
      

(fieldname1,fieldname2…) VALUES (value1,value2);

INSERT INTO customers (customerID,password,firstName,lastName,

address,city,state,zip,phone)

VALUES

('victrolafirecracker','test','Victrola','Firecracker','909 S Boston Ave','Tulsa','OK','74119','9185957060');

INSERT INTO customers (customerID,password,firstName,lastName)

VALUES ('jjackson','johnjohn','John','Jackson');

INSERT INTO customers (customerID,password,firstName,lastName)

VALUES ('jjohnson','jackjack','Jack','Johnson');

INSERT INTO employees (employeeID,password,firstName,lastName,securityLevel) VALUES ('victrola','test','Victrola','Firecracker','9');

INSERT INTO employees (employeeID,password,firstName,lastName,securityLevel) VALUES ('bob','password','Bob','Bobson','0');

INSERT INTO books (ISBN,Title,Author,Category,Price)

VALUES ('0619034424','Web Warrior Series - ColdFusion','Kaparthi','Programming','30.00');

INSERT INTO books (ISBN,Title,Author,Category,Price)

VALUES ('0321125169','ColdFusion - Web Application Construction Kit','Forta and Weiss','Programming','50.00');

INSERT INTO books (ISBN,Title,Author,Category,Price) VALUES ('0553377876','Half Asleep in Frog Pajamas

','Tom Robbins','Fiction','10.46');

INSERT INTO books (ISBN,Title,Author,Category,Price) VALUES ('034530988X','Friday','Robert Heinleid','Science Fiction','6.29');

INSERT INTO orders (customerID,date) VALUES ('jjackson','2005-02-14');

INSERT INTO orderItems (ISBN,orderNumber) VALUES ('0321125169','1');

INSERT INTO orderItems (ISBN,orderNumber) VALUES ('0553377876','1');

Updating Data with SQL

UPDATE tablename
  SET fieldname1 = value1, fieldname2 = value2 …
  [WHERE condition]

      

UPDATE customers

SET phone = '9185550001'

WHERE customerID = 'jjackson';

UPDATE customers

SET city = 'New York'

WHERE customerID = 'jjackson'

   OR customerID = 'jjohnson';

Deleting Data with SQL

DELETE FROM tablename
  [WHERE condition]

DELETE FROM employees WHERE employeeID = "bob";

Extracting Data with SQL

SELECT fieldname1, fieldname2, … FROM tablename;
SELECT firstName, lastName FROM customers;
SELECT Title, Price, Category from books;
SELECT * FROM employees;
SELECT lastName, phone
      

FROM customers

WHERE city = 'New York';

SELECT title, price FROM books WHERE price > 10.00;
SELECT password FROM employees WHERE employeeID = 'victrola';
SELECT * FROM books WHERE price BETWEEN 10.00 AND 40.00;
SELECT * FROM customers WHERE city IN ('Tulsa','New York');
SELECT * FROM books WHERE title LIKE '%half%';
SELECT * FROM books ORDER BY price;
SELECT * FROM books ORDER BY price DESC;
SELECT * FROM customers ORDER BY lastname, firstname;
SELECT title FROM books WHERE ISBN IN (
      

SELECT ISBN FROM orderItems WHERE orderNumber IN (

SELECT orderNumber FROM orders WHERE customerID = 'victrolafirecracker'))

SELECT DISTINCT city FROM customers;
SELECT count(*) AS totalCustomers FROM customers;
SELECT sum( price ) AS totalBookPriceInStock FROM books;
SELECT sum( price ) FROM books WHERE ISBN IN (
      

SELECT ISBN FROM orderItems WHERE orderNumber IN (

SELECT orderNumber FROM Orders WHERE customerID = 'jjackson'))

SELECT count(*) FROM customers WHERE city = "New York" GROUP BY city;

Accessing MySQL from a PHP Web Page

How web database architecture works

  1. A client request a php page from a server
  2. The web server receives the request
  3. The web server sees that it is a PHP page so passes the page to the PHP server
  4. The PHP server parses and executes the php statements in the page
  5. When the php server sees a command to connect to a database server so it does
  6. The php server sees a statement that tells it to issue an sql statement against a database
  7. The database server returns the results of the sql statement
  8. The php pages codes then tell the php server how to work with the returned data from the query
  9. The results are formatted and returned to the user as the pages output.

Querying a Database from the Web

Checking and Filtering results from the user

Setting up the connection to the database

create table categorys (
  idintnot null auto_increment,
  namevarchar( 50 ) not null,
  PRIMARY KEY (id)
      

)

insert into categorys (name) values ('food');

insert into categorys (name) values ('carpet');

//object oriented approach
$db = new mysqli( ‘hostname’, ‘username’, ‘password’, ‘databasename’ );
//procedural approach
$db = mysqli_connect( ‘hostname’, ‘username’, ‘password’, ‘databasename’ );
//both techniques
if( mysqli_connect_errno( ) ) {
  echo "Could not connect to the DB";
  exit;
}

Choosing a Database to Use

//object oriented
$db->select_db( ‘dbname’ );

//procedural
mysqli_select_db( $db, ‘dbname’ );

Querying the Database

//object oriented
$result = $db->query( $query );

//procedural
$result = mysqli_query( $db, $query );

Working with the Query Results

//OO
$num_of_rows = $result->num_rows;

//procedural
$num_of_rows = mysqli_num_rows( $result );
//OO
$row = $result->fetch_assoc( );

//procedural
$row = mysqli_fetch_assoc( $result );
//OO
$row = $result->fetch_row( );

//procedural
$row = mysqli_fetch_row( $result );
//OO
$row = $result->fetch_array( MYSQLI_NUM );

//procedural
$row = mysqli_fetch_array( $result, MYSQLI_ASSOC );

//OO again
$row = $result->fetch_array( MYSQLI_BOTH );
//OO
$row = $result->fetch_object( );

//procedural
$row = mysqli_fetch_object( $result );

echo $row->name;
echo $row->id;

Disconnecting

$result->free( ); //OO

      

mysqli_free_result( $result ); //procedural

$db->close( ); //OO

      

mysqli_close( $db ); //procedural

create table categorys (
  idintnot null auto_increment,
  namevarchar( 50 ) not null,
  PRIMARY KEY (id)
      

)

create table samples (

idintnot null auto_increment, descriptiontextnot null, pricefloat not null, categoryintnot null, PRIMARY KEY (id), FOREIGN KEY (category) REFERENCES categorys(id)

)

insert into categorys (name) values ('food');

insert into categorys (name) values ('drug');

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>View Categories</title>
  </head>

  <body>
    <h1>View - Categories</h1>
    <?php
      $db = new mysqli( 'localhost', 'mysql', '', 'phpexamples');
      //$db = mysqli_connect('localhost','mysql','',
                            'phpexamples');

      if( mysqli_connect_errno( ) ) {
        echo "The database could not be contacted";
        exit;
      }

      $query = "select * from categorys order by name";

      $result = $db->query( $query );
      //$result = mysqli_query( $db, $query );

      echo $result->num_rows . " categories found.";
      //echo mysqli_num_rows( $result ) . " categories found";

      if( $result->num_rows == 0 ) {
      //if( mysqli_num_rows( $result ) == 0 ) {
        echo "No Categories Found.";
      } else {
        echo '<table border="1" cellspacing="0"
                        cellpadding="5">';
        echo '<tr><th></th><th>Name</th></tr>';
        for( $x = 0 ; $x < $result->num_rows ; $x++ ) {
        //for($x = 0 ; $x < mysqli_num_rows( $result ) ; $x++ ) {
          $row = $result->fetch_assoc( );
          //$row = mysqli_fetch_assoc( $result );
          echo '<tr>';
          echo '<td>' . $row[ 'id' ] . '</td>';
          echo '<td>' . $row[ 'name' ] . '</td>';
          echo '</tr>';
        }
        echo '</table>';
      }
    ?>
  </body>
</html>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Add Categories</title>
  </head>

  <body>
    <h1>Add - Categories</h1>

    <?php
      if( isset( $_POST[ 'newcat' ] ) ) {
        if( $_POST[ 'newcat' ] != "" ) {
          $newcat = htmlspecialchars(trim($_POST[ 'newcat' ]));

          $db = new mysqli('localhost','mysql',
                    '','phpexamples');

          //check values for duplicates
          $query = "select name from categorys where name='" .
                            $newcat . "'";

          $result = $db->query( $query );

          if( $result->num_rows > 0 ) {
            echo "That category already exists";
          } else {
            $query = "INSERT INTO categorys (name) VALUES ('" .
                            $newcat . "')";
            $result = $db->query( $query );

            echo "Affected Rows: " . $db->affected_rows .
                              "<br/>";
            if( $db->affected_rows > 0 ) {
              echo "New Category Added<br/>";
              echo '<a href="ViewCategories.php">Go see
                              it</a>';
              exit;
            } else {
              echo "No Changes were made!?!<br/>";
            }
          }
        } else {
          echo "You must supply a new category name";
        }
      }
    ?>

    <form action="addcategories.php" method="post">
      <table>
        <input type="text" name="newcat"/>
        <input type="submit" value="Add Category"/>
      </table>
    </form>
  </body>
</html>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Remove Categories</title>
  </head>

  <body>
    <h1>Remove - Categories</h1>

    <?php
      @ $db = new mysqli('localhost','mysql','','phpexamples');

      if( mysqli_connect_errno( ) ) {
        echo "Could not connect to the database.";
        exit;
      }

      if( isset( $_POST[ 'remove' ] ) ) {
        echo "there are categories to be removed.<br/>";

        $removals = $_POST[ 'remove' ];

        foreach( $removals as $cur ) {
          echo "removing " . $cur . "<br/>";
          $query = "delete from categorys where id='" . $cur .
                                "'";
          $db->query( $query );
        }
      }

      $query = 'select * from categorys order by name';

      $results = $db->query( $query );

      if( $results->num_rows > 0 ) {

      } else {
        echo "The table appears to be empty.";
        exit;
      }
    ?>

    <form action="RemoveCategories.php" method="post">
      <table border="1" cellspacing="0" cellpadding="5">
        <tr><th>Name</th><th>X</th></tr>
        <?php
          for( $x = 0 ; $x < $results->num_rows ; $x++ ) {
            $row = $results->fetch_object( );
            echo '<tr>';
            echo '<td>' . $row->name . '</td>';
            echo '<td><input type="checkbox" value="' . $row->id
                    . '" name="remove[ ]"/></td>';
            echo '</tr>';
          }
        ?>
      </table>
      <input type="submit" value="Remove Selected Categories"/>
    </form>
  </body>
</html>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Edit Categories</title>
  </head>

  <body>
    <h1>Edit Categories</h1>
    Choose a category to edit:
    <table>
      <?php
        @ $db = new mysqli('localhost','mysql','','phpexamples');

        if( mysqli_connect_errno( ) ) {
          echo "Could not connect to the database.";
          exit;
        }

        if( isset( $_GET[ 'id' ] ) ) {
          $query = "select * from categorys where id='"
                        . $_GET[ 'id' ] . "'";
          $result = $db->query( $query );
          $cat = $result->fetch_object( );
          ?>
            <form action="EditCategories.php" method="post">
              <br/><input type="text" name="newcat"
                  value="<?php echo $cat->name; ?>"/><br/>
              <input type="hidden" name="id" value="
                        <?php echo $cat->id; ?>"/>
              <input type="submit" value="Submit Change"/>
            </form>
          <?php
          exit;
        }

        if( isset( $_POST[ 'newcat' ] ) ) {
          if( $_POST[ 'newcat' ] != "" ) {
            $newcat = htmlspecialchars(trim($_POST['newcat']));

            $query = "update categorys set name='" . $newcat
                  . "' where id='" . $_POST[ 'id' ] . "'";
            $db->query( $query );
          } else {
            echo "The category must have a name";
            exit;
          }
        }

        $query = "select * from categorys order by name";
        $result = $db->query( $query );

        for( $x = 0 ; $x < $result->num_rows ; $x++ ) {
          $row = $result->fetch_assoc( );
          echo '<tr>';
          echo '<td><a href="EditCategories.php?id='
          . $row[ 'id' ] . '">' . $row[ 'name' ] . '</a></td>';
          echo '</tr>';
        }
      ?>
    </table>
  </body>
</html>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Search Categories</title>
  </head>

  <body>

    <?php
      @ $db = new mysqli('localhost','mysql','','phpexamples');

      if( mysqli_connect_errno( ) ) {
        echo "The database could not be opened.";
        exit;
      }
    ?>

    <h1>Search Categories</h1>

    <form action="SearchCategories.php" method="post">
      Search for Category:
      <input type="text" name="searchterm"/>
      <input type="submit" value="Search"/>
    </form>

    <?php
      if( isset( $_POST[ 'searchterm' ] ) ) {
        if( $_POST[ 'searchterm' ] != "" ) {
          $term = htmlspecialchars(trim($_POST['searchterm']));


          $query = "select * from categorys where name like '%"
                          . $term . "%'";
          $results = $db->query( $query );

          if( $results->num_rows > 0 ) {
            echo '<ol>';
            for( $x = 0 ; $x < $results->num_rows ; $x++ ) {
              $row = $results->fetch_object( );
              echo '<li>' . $row->name . '</li>';
            }
            echo '</ol>';
          } else {
            echo "No matches were found";
          }

        } else {
          echo "You must supply a category to search for.";
        }
      }
    ?>
  </body>
</html>

Interacting with the Server's Filesystem

Uploading Files

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Upload a file</title>
  </head>

  <body>
    <h2>Upload a File</h2>
    <form enctype="multipart/form-data" method="post"
         action="FileUploadReceive.php">
      <input type="hidden" name="MAX_FILE_SIZE" value="2000000"/>
      <input type="file" name="uploadedfile"/><br/>
      <input type="submit" value="Upload File Now"/>
    </form>
  </body>
</html>

Using PHP to Deal with Uploaded Files

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>File Upload Received</title>
  </head>

  <body>
    <h2>File Information</h2>
    <?php
      echo "File name on server: "
          . $_FILES[ 'uploadfile' ][ 'tmp_name' ] . "<br/>";
      echo "Original filename: "
          . $_FILES[ 'uploadfile' ][ 'name' ] . "<br/>";
      echo "Size of file: "
          . $_FILES[ 'uploadfile' ][ 'size' ] . " bytes<br/>";
      echo "File type: "
          . $_FILES[ 'uploadfile' ][ 'type' ] . "<br/>";
      echo "Errors: "
          . $_FILES[ 'uploadfile' ][ 'error' ] . "<br/>";
      if( $_FILES[ 'uploadfile' ][ 'error' ] > 0 ) {
        echo "Error explanation: <br/>";
        switch( $_FILES[ 'uploadfile' ][ 'error' ] ) {
          case 1:
            echo "File exceeds upload_max_filesize
                          (from PHP.INI)";
            break;
          case 2:
            echo "File exceeds max_file_size
                        (from upload form)";
            break;
          case 3:
            echo "File upload not complete";
            break;
          case 4:
            echo "No file uploaded";
            break;
        }
        exit;
      }

      $destination = "./" . $_FILES[ 'uploadfile' ][ 'name' ];

      if( is_uploaded_file( $_FILES[ 'uploadfile' ][ 'tmp_name' ] ) ) {
        if( ! move_uploaded_file(
            $_FILES[ 'uploadfile' ][ 'tmp_name' ],
            $destination ) ) {
          echo "Could not move the file to the destination directory";
          exit;
        }
      } else {
        echo "Possible file upload attack with filename "
            . $_FILES[ 'uploadfile' ][ 'tmp_name' ]
            . "(" . $_FILES[ ‘uploadfile’ ][ ‘name’ ] . ")";
      }

      echo "<h2>File upload completed successfully</h2>";

    ?>
  </body>
</html>

Security Concerns with Uploading Files

Using Directory Functions

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>File Upload Received</title>
  </head>

  <body>
    <?php
      echo '<h2>File Information</h2>';

      echo "File name on server: "
          . $_FILES[ 'uploadfile' ][ 'tmp_name' ] . "<br/>";
      echo "Original filename: "
          . $_FILES[ 'uploadfile' ][ 'name' ] . "<br/>";
      echo "Size of file: "
          . $_FILES[ 'uploadfile' ][ 'size' ] . " bytes<br/>";
      echo "File type: "
          . $_FILES[ 'uploadfile' ][ 'type' ] . "<br/>";
      echo "Errors: "
          . $_FILES[ 'uploadfile' ][ 'error' ] . "<br/>";
      if( $_FILES[ 'uploadfile' ][ 'error' ] > 0 ) {
        echo "Error explanation: <br/>";
        switch( $_FILES[ 'uploadfile' ][ 'error' ] ) {
          case 1:
            echo "File exceeds upload_max_filesize
                        (from PHP.INI)";
            break;
          case 2:
            echo "File exceeds max_file_size
                        (from upload form.html)";
            break;
          case 3:
            echo "File upload not complete";
            break;
          case 4:
            echo "No file uploaded";
            break;
        }
        exit;
      }

      if( ! is_dir( './uploads' ) ) {
        mkdir( 'uploads', 0777 );
      }

      $destination = "./uploads/"
                  . $_FILES[ 'uploadfile' ][ 'name' ];

      if( is_uploaded_file(
          $_FILES[ 'uploadfile' ][ 'tmp_name' ] ) ) {
        if( ! move_uploaded_file(
            $_FILES[ 'uploadfile' ][ 'tmp_name' ],
            $destination ) ) {
          echo "Could not move the file to the destination
                            directory";
          exit;
        }
      } else {
        echo "Possible file upload attack with filename "
            . $_FILES[ 'uploadfile' ][ 'tmp_name' ]
            . "(" . $_FILES[ 'uploadfile' ][ 'name' ] . ")";
      }
      echo "<h2>File upload completed successfully</h2>";

      if( $dir = opendir( 'uploads' ) ) {
        echo "Uploaded files:<br/>";
        while( $file = readdir( $dir ) ) {
          if( $file != "." && $file != ".." ) {
            echo $file . "<br/>";
          }
        }

        closedir( $dir );
      }
    ?>
  </body>
</html>

Getting Information about specific files

Program Execution Functions

string exec(string command [, array &results [, int &returncode]])
void passtatementru( string command [, int returncode] )
string system( string command [, int &returncode] )

Interacting with the Servers Environment

Network and Protocol Functions

Examining Available Protocols

Sending and Reading Email

// Email form
<?php echo '<?xml version="1.0" encoding="UTF-8"?>' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
    <title>Email Me</title>
  </head>

  <body>
    <h1>Email Me</h1>

    <form enctype="multipart/form-data"
         action="receiveEmail.php" method="POST">
      <!-- to: -->
      to: Victrola Firecracker&lt;victrola@firecracker.org&gt;
      <br/>

      <!--from name -->
      your name: <input type="text" name="name"/>
      <br/>

      <!-- from address -->
      your address: <input type="text" name="address"/>
      <br/>

      <!-- subject: -->
      subject: <input type="text" name="subject"/>
      <br/>

      <!-- body: -->
      body:<br/>
      <textarea name="body"></textarea>

      <!-- MAX_FILE_SIZE is about 5MB -->
      <input type="hidden" name="MAX_FILE_SIZE"
            value="5000000" />
      <br/>

      <!-- file select control -->
      Send this file: <input name="userfile" type="file" /><br/>
      <input type="submit" value="Send File" />
    </form
  </body>
</html>
// Receive email action script
<?php
$DEBUG = true;

//what type of email is this? submitted homework or a regular email
$emailType = "";

if( $_POST[ 'name' ] != "" && $_POST[ 'address' ] != "" && $_POST[ 'subject' ] != "" && $_POST[ 'body' ] != "" ) {
  $emailType = "regular";
} else if( $_POST[ 'name' ] != "" && $_POST[ 'address' ] != "" ) {
$emailType = "homework";
} else {
  echo "There are required fields missing<br/>";
  exit;
        }

if( DEBUG ) echo "Email type is " . $emailType . "<br/>";

//receive the uploaded attachment
$uploaddir = './tmp/';

$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

            

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {

echo "File is valid, and was successfully uploaded.<br/>"; } else { $errorNo = $_FILES['userfile']['error']; if( $errorNo == 0 ) { echo "Wait a second. This isn't an error. nevermind. wait. yes it is. look above.<br/>"; } else if( $errorNo == 1 ) { echo "Your file exceeds the maximum upload limit (It's to big) set by the server.<br/>"; } else if( $errorNo == 2 ) { echo "Your file exceeds the maximum upload limit (It's to big).<br/>"; } else if( $errorNo == 3 ) { echo "It appears the upload was interrupted. Please try again.<br/>"; } else if( $errorNo == 4 ) { echo "No attachment detected.<br/>"; } else if( $errorNo == 5 ) { echo "Missing temporary folder. Please report this to the webmaster.<br/>"; } else if( $errorNo == 6 ) { } //no point in submitting a homework email with no homework //attached. if( $emailType == "homework" ) { exit; } } //prep the email

require("class.phpmailer.php");

$mail = new PHPMailer(); $mail->From     = $_POST['address']; $mail->FromName = $_POST['name']; $mail->Host     = "mail.thesingers.info"; $mail->Mailer = "smtp"; $subject = ""; $body = ""; $text_body = ""; //Build the email //email subject if( $emailType == "homework" ) { $subject = "Homework from " . $_POST['name']; } else { $subject = $_POST[ 'subject' ]; } //email body if( $emailType == "homework" ) { $body = "<p>A homework assignment has been submitted by <strong>" . $_POST['name'] . "</strong></p>"; // Plain text body (for mail clients that cannot read HTML) $text_body = "A homework assignment has been submitted by " . $_POST['name'] . "\n\n"; } else { $body = $_POST[ 'body' ]; $text_body = $body; } $mail->Subject = $subject; $mail->Body    = $body; $mail->AltBody = $text_body; $mail->AddAddress("victrola@firecracker.org", "Victrola Firecracker"); $mail->AddAttachment($uploadfile); if( !$mail->Send() ) { echo "There has been a mail error sending to victrola@firecracker.org<br/>"; echo "Go back and make sure the email address you specified is valid."; //echo "Mailer Error: " . $mail->ErrorInfo; } else { echo "Email sent!"; } // Clear all addresses and attachments for next loop $mail->ClearAddresses(); $mail->ClearAttachments();

unlink( $uploadfile ); //delete file from tmp folder

?>

Using Other Websites

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Tulsa Temperature</title>
  </head>

  <body>
  <h1>Current Tulsa Temperature</h1>
    <?php
      $url = "http://www.weather.gov/data/current_obs/KRVS.xml";
      if( ! ($content = file_get_contents( $url ))) {
        echo "Could not open url";
        exit;
      }

      $temppattern = '<temp_f>.*</temp_f>';
      if( eregi( $temppattern, $content, $temp_f ) ) {
        echo strip_tags($temp_f[ 0 ]) . "&deg; F";
      } else {
        echo "No Current Temp Available";
      }

      $chillpattern = '<windchill_f>.*</windchill_f>';
        if( eregi( $chillpattern, $content, $chill_f ) ) {
        echo " but it feels like " . strip_tags($chill_f[ 0 ]) . "&deg; F";
      } else {
        echo "No Windchill Info Available";
      }
    ?>
  </body>
</html>

Using Network Lookup Functions

string gethostbyname ( string hostname )
string gethostbyaddr ( string ip_address )
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>untitled</title>
  </head>
  <body>
    <?php
      $host = "threesuns.org";

      $ip = gethostbyname( $host );
      echo "The IP address for " . $host . " is " . $ip;

      $actualhost = gethostbyaddr( $ip );
      echo "<br/>The actual host name for that address is " . $actualhost;
    ?>
  </body>
</html>
bool dns_get_mx (string hostname, array &mxhosts [, array &weight])
int checkdnsrr ( string host [, string type] )

Using FTP

resource ftp_connect ( string host [, int port [, int timeout]] )

bool ftp_close ( resource ftp_stream )

bool ftp_login ( resource ftp_stream, string username, string password )

bool ftp_cdup ( resource ftp_stream )

bool ftp_chdir ( resource ftp_stream, string directory )

array ftp_nlist ( resource ftp_stream, string directory )

bool ftp_get ( resource ftp_stream, string local_file, string remote_file, int mode [, int resumepos] )

bool ftp_put ( resource ftp_stream, string remote_file, string local_file, int mode [, int startpos] )

int ftp_size ( resource ftp_stream, string remote_file )

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>FTP</title>
  </head>

  <body>
  <?php
    $host = "ftp.mozilla.org";
    $path = "/pub/mozilla.org/firefox/releases/1.5/win32/en-US/";
    $user = "anonymous";
    $password = "victrola@firecracker.org";

    echo "<h2>FTP'd to " . $host . "</h2>";

    $conn = ftp_connect( $host );
    if( ! $conn ) {
      echo "Could not connect to " . $host;
      exit;
    } else {
      echo "Connected to " . $host . "<br/>";
    }

    $loggedin = ftp_login( $conn, $user, $password );
    if( ! $loggedin ) {
      echo "Could not login to " . $host;
      exit;
    } else {
      echo "Logged into " . $host . "<br/>";
    }

      $mode = ftp_pasv( $conn, true );

      if( isset( $_GET[ 'getfile' ] ) ) {
        echo "Getting file " . $_GET[ 'getfile' ] . "<br/>";
        ftp_get( $conn, basename( $_GET[ 'getfile' ] ), $_GET[ 'getfile' ], $mode );
        echo '<a href="' . basename( $_GET[ 'getfile' ] ) . '">File retrieved</a><br/>';
      } else {
        $files = ftp_nlist( $conn, $path );

set_time_limit( 120 );

foreach( $files as $file ) { echo '<a href="' . $_SERVER['PHP_SELF'] . '?getfile=' . $file . '">' . $file . '</a>' . "<br/>"; } } ftp_quit( $conn ); echo "Logged out and connection closed.<br/>" ?> </body> </html>

Generating Images

Image Formats

Creating Images

<?php
  header("Content-type: image/png");

  $width = 120;
  $height = 25;

  // Create image and define colors
  $image = imagecreatetruecolor( $width, $height );

  //the first color allocated is the background???
  $white = imagecolorallocate( $image, 255,255,255 );
  $green = imagecolorallocate( $image, 0,150,0 );

  imagefill( $image, 0, 0, $green );

  imagestring( $image, 5, 3, 5, "Hello, World!", $white );

  imagepng( $image );
  imagedestroy( $image );
?>
<img src="HelloWorld.php" alt="HelloWorld"/>
imagepng( $image, "newimage.png" );

Creating a Canvas

Drawing on a Canvas

int imagecolorallocate(resource image, int red,int green,int blue)
bool imagefill ( resource image, int x, int y, int color )
bool imageline(resource image, int x1, int y1, int x2, int y2, int color)

bool imagerectangle ( resource image, int x1, int y1, int x2, int y2, int col )

bool imageellipse ( resource image, int cx, int cy, int w, int h, int color )

bool imagepolygon ( resource image, array points, int num_points, int color )

bool imagefilledrectangle ( resource image, int x1, int y1, int x2, int y2, int color )

bool imagefilledellipse ( resource image, int cx, int cy, int w, int h, int color )

bool imagefilledpolygon ( resource image, array points, int num_points, int color )

<?php
  header("Content-type: image/png");
  $width=200;
  $height=50;

  // Create image and define colors
  $image = imagecreatetruecolor( $width, $height );

  $background = imagecolorallocate( $image, 255, 255, 255 );
  imagefill( $image, 0, 0, $background );

  $color = imagecolorallocate( $image, 100, 100, 255 );

  ImageRectangleWithRoundedCorners( $image, 0, 0, $width, $height, 15, $color );

  imagepng( $image );
  imagedestroy( $image );

  function ImageRectangleWithRoundedCorners( &$im, $x1, $y1, $x2,
                        $y2, $radius, $color ) {
    // draw rectangle without corners
    imagefilledrectangle( $im, $x1+$radius, $y1, $x2-$radius, $y2, $color );
    imagefilledrectangle( $im, $x1, $y1+$radius, $x2, $y2-$radius, $color );
    // draw circled corners
    imagefilledellipse( $im, $x1+$radius, $y1+$radius, $radius*2, $radius*2, $color );
    imagefilledellipse( $im, $x2-$radius, $y1+$radius, $radius*2, $radius*2, $color );
    imagefilledellipse( $im, $x1+$radius, $y2-$radius, $radius*2, $radius*2, $color );
    imagefilledellipse( $im, $x2-$radius, $y2-$radius, $radius*2, $radius*2, $color );
  }
?>

Using Text and Font on Images

bool imagestring ( resource image, int font, int x, int y, string s, int col )
array imagettftext ( resource image, float size, float angle, int x, int y, int color, string fontfile, string text )
putenv( 'GDFONTPATH=/Users/victrola/Library/Fonts' );
array imagettfbbox ( float size, float angle, string fontfile, string text )
0 lower left corner, X position
1 lower left corner, Y position
2 lower right corner, X position
3 lower right corner, Y position
4 upper right corner, X position
5 upper right corner, Y position
6 upper left corner, X position
7 upper left corner, Y position
//////////////////////////////////////////////////////////////////
// Put center-rotated ttf-text into image
// Same signature as imagettftext();
//////////////////////////////////////////////////////////////////
function imagettftext_cr(&$im, $size, $angle, $x, $y, $color, $fontfile, $text) {
  // retrieve boundingbox
  $bbox = imagettfbbox($size, $angle, $fontfile, $text);

  // calculate deviation
  // deviation left-right
  $dx = ($bbox[2]-$bbox[0])/2.0 - ($bbox[2]-$bbox[4])/2.0;
  // deviation top-bottom
  $dy = ($bbox[3]-$bbox[1])/2.0 + ($bbox[7]-$bbox[1])/2.0;

  // new pivotpoint
  $px = $x-$dx;
  $py = $y-$dy;

  return imagettftext($im, $size, $angle, $px, $py, $color, $fontfile, $text);
}

Session Management and Cookies

What is a session?

Basic Session Functionality

What is a Cookie?

Setting Cookies from PHP

bool setcookie( string name [, string value [, int expires [, string path [, strring domain [, int secure]]]]] )
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
    <title>Cookie Test</title>
  </head>
  <body>
    <?php
      if( isset( $_POST[ 'newcookiename' ] ) ) {
        $name = $_POST[ 'newcookiename' ];
        $value = $_POST[ 'newcookievalue' ];

        if( setcookie( $name, $value ) ) {
          header( 'location:' . $_SERVER[ 'PHP_SELF' ] );
        }
      }
    ?>

    <h1>Cookie Test</h1>
    <form action="<?php echo $_SERVER[ 'PHP_SELF' ] ?>"
         method="post">
      New Cookies Name:
      <input type="text" name="newcookiename"/><br/>
      New Cookies Value:
      <input type="text" name="newcookievalue"/><br/>
      <input type="submit" value="Create new cookie"/>
    </form>

    <?php
      echo count( $_COOKIE ) . " cookies<br/><br/>";
      foreach( $_COOKIE as $name => $value ) {
        echo $name . " = " . $value . "<br/>";
      }
    ?>

  </body>
</html>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Cookie Test</title>
  </head>

  <body>

    <?php
      //add new cookies
      if( isset( $_POST[ 'newcookiename' ] ) ) {
        $name = $_POST[ 'newcookiename' ];
        $value = $_POST[ 'newcookievalue' ];

        $expires = time( ) + 60; //expires in 1 minute

        if( setcookie( $name, $value, $expires ) ) {
          header( 'location:' . $_SERVER[ 'PHP_SELF' ] );
        }
      }
    ?>

    <?php
      //delete old cookies
      if( isset( $_GET[ 'cname' ] ) ) {
        $name = $_GET[ 'cname' ];

        $expires = time( ) - 1; //expires in 1 minute

        if( setcookie( $name, "", $expires ) ) {
          header( 'location:' . $_SERVER[ 'PHP_SELF' ] );
        }
      }
    ?>

    <h1>Cookie Test</h1>
    <form action="<?php echo $_SERVER[ 'PHP_SELF' ] ?>"
         method="post">
      New Cookies Name:
      <input type="text" name="newcookiename"/><br/>
      New Cookies Value:
      <input type="text" name="newcookievalue"/><br/>
      <input type="submit" value="Create new cookie"/>
    </form>

    <?php
      echo count( $_COOKIE ) . " cookies<br/><br/>";
      foreach( $_COOKIE as $name => $value ) {
        echo $name . " = " . $value
            . " <a href=\"" . $_SERVER[ 'PHP_SELF' ]
            . "?cname=" . $name . "\">Delete this
                        cookie</a><br/>";
      }
    ?>

  </body>
</html>

Using Cookies with Sessions

Implementing Simple Sessions

Starting a Session

session_start( );

Registering Session Variables

$_SESSION[ ‘bgcolor’ ] = "black";

Using Session Variables

echo $_SESSION[ ‘bgcolor’ ];

Unsetting Session Variables and Destroying a Session

unset( $_SESSION[ ‘bgcolor’ ] );
$_SESSION = array( );
session_destroy( );
<?php
  session_start( );
?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Page 1</title>
  </head>

  <?php
    if( isset( $_POST[ 'bgcolor' ] ) ) {
      $_SESSION[ 'bgcolor' ] = $_POST[ 'bgcolor' ];
    }
  ?>

  <style type="text/css">
    body {
      background-color:
      <?php
        if( ! empty( $_SESSION[ 'bgcolor' ] ) ) {
          echo $_SESSION[ 'bgcolor' ];
        } else {
          echo "white";
        }
      ?>
      ;
    }
  </style>

  <body>
    <h1>Page 1</h1>
    <div id="nav">
      <ul>
        <li><a href="page1.php">Page 1</a></li>
        <li><a href="page2.php">Page 2</a></li>
        <li><a href="page3.php">Page 3</a></li>
      </ul>
    </div>
    <form action="<?php echo $_SERVER[ 'PHP_SELF' ] ?>"
         method="post">
      Choose a background color:
      <select name="bgcolor">
        <option>White</option>
        <option>Red</option>
        <option>Yellow</option>
        <option>Green</option>
      </select>
      <br/>
      <input type="submit" value="Change Color"/>
    </form>
  </body>
</html>

<?php
  session_start( );
?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Page 2</title>

    <style type="text/css">
    body {
      background-color:
      <?php
        if( ! empty( $_SESSION[ 'bgcolor' ] ) ) {
          echo $_SESSION[ 'bgcolor' ];
        } else {
          echo "white";
        }
      ?>
      ;
    }
  </style>

  </head>

  <body>
    //include title and nav div here
  </body>
</html>

<?php
  session_start( );
?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Page 3</title>

    <?php
      if( isset( $_GET[ 'reset' ] ) ) {
        $_SESSION = array( );
        session_destroy( );
      }
    ?>

  <style type="text/css">
    body {
      background-color:
      <?php
        if( ! empty( $_SESSION[ 'bgcolor' ] ) ) {
          echo $_SESSION[ 'bgcolor' ];
        } else {
          echo "white";
        }
      ?>
      ; /* ending ; for css attribute */
    }
  </style>

  </head>

  <body>
    //include title and nav div here

    <a href="<?php echo $_SERVER[ 'PHP_SELF' ] ?>?reset=true">
      Reset Session
    </a>
  </body>
</html>

PDO Based Database Access

PDO = PHP Data Objects

Why use PDO instead of mysqli?

Database Support

Currenlty Available Drivers:

Driver name Supported Databases
PDO_CUBRID Cubrid
PDO_DBLIB FreeTDS / Microsoft SQL Server / Sybase
PDO_FIREBIRD Firebird
PDO_IBM IBM DB2
PDO_INFORMIX IBM Informix Dynamic Server
PDO_MYSQL MySQL 3.x/4.x/5.x
PDO_OCI Oracle Call Interface
PDO_ODBC ODBC v3 (IBM DB2, unixODBC and win32 ODBC)
PDO_PGSQL PostgreSQL
PDO_SQLITE SQLite 3 and SQLite 2
PDO_SQLSRV Microsoft SQL Server / SQL Azure
PDO_4D 4D
//Find out which drivers you have with:
print_r(PDO::getAvailableDrivers( ));

How to Connect to the DB Server:

//common connections
try {
  //MS SQL Server
  $db = new PDO("mssql:host=$host;dbname=$dbname, $user, $pass");

  //MySQL
  $db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);

  //SQLite
  $db = new PDO("sqlite:my/database/path");
} catch(PDOException $e) {
  echo $e->getMessage();
}
You can close any connection by setting the handle to null.
//close the connection
$db = null;

Exceptions and PDO

Always wrap your PDO operations in a try/catch. Exceptions are how PDO handles all of it's errors.

$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

Default is to not throw exceptions but this isn't very useful, or not as useful as it could be

PDO::ERRMODE_SILENT

Give PHP warning, program keeps executnig so you miss it if you're not looking

PDO::ERRMODE_WARNING

The best mode. Errors throw exceptions that aren't easily missed and are very descriptive

PDO::ERRMODE_EXCEPTION
try {
$db = new PDO("mysql:host=$host; dbname=$dbname", $user, $pass);
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$db->prepare('DELECT title FROM songs'); //<-- OOPS!
} catch(PDOException $e) {
  echo "A PDO Exception has Occurred";
}

Inserting and Updating

$statement = $db->prepare("INSERT INTO songs ( title ) values ( 'Mermaid Smiled' )");
$statement->execute();

Prepared Statements

Using prepared statements will help protect you from SQL injection.

Prepared statements by including a placeholder in the SQL code.

//BAD!
$statement = $db->prepare("INSERT INTO songs (title, duration, tracknumber) values ($title, $duration, $tracknumber)");

Unnamed Placeholders

//unnamed placeholders, gets confusing when there are many of them
$statement = $db->prepare("INSERT INTO songs (title, duration, tracknumber) values (?, ?, ?)");

//assign variables to each place holder, indexed 1-3
$statement->bindParam(1, $title);
$statement->bindParam(2, $duration);
$statement->bindParam(3, $tracknumber);

//insert one row
$title = "Mermaid Smiled"
$duration = "3:20";
$tracknumber = 3;
$statement->execute();

//insert another row with different values
$title = "That Wave"
$duration = "2:50";
$tracknumber = 9;
$statement->execute();

//another way that doesn't require the binding step
$data = array('Mermaid Smiled', '3:20', 3);
$statement = $db->prepare("INSERT INTO songs (title, duration, tracknumber) values (?, ?, ?)");
$statement->execute($data);

Named Placeholders

//named placeholders
$statement = $db->prepare("INSERT INTO songs (title, duration, tracknumber) value (:title, :duration, :tracknumber)");

//placeholders can start with a colon but don't have to
$statement->bindParam(':title', $title);

//the data we want to insert
$data = array( 'title' => 'Mermaid Smiled', 'duration' => '3:20', 'tracknumber' => 3 );

//the array shortcut
$statement = $db->prepare("INSERT INTO songs (title, druation, tracknumber) value (:title, :duration, :tracknumber)");
$statement->execute($data);

Inserting Objects

Objects can be inserted into the database if their property names match the field names

class song {
  public $title;
  public $duration;
  public $tracknumber;
    function __construct($t,$d,$t) {
      $this->title = $t;
      $this->duration = $d;
      $this->tracknumber = $t;
    }
    // ...
  }
$mermaid = new song('Mermaid Smiled','3:20',3);

$statement = $db->prepare("INSERT INTO songs (title, duration, tracknumber) value (:title, :duration, :tracknumber)");
$statement->execute((array)$mermaid);

Selecting Data

fetch() gets data from the database. Needs to know in what format to return it:

PDO::FETCH_ASSOCreturns an array indexed by column name
PDO::FETCH_BOTH (default)returns an array indexed by both column name and number
PDO::FETCH_BOUNDAssigns the values of your columns to the variables set with the ->bindColumn() method
PDO::FETCH_CLASSAssigns the values of your columns to properties of the named class. It will create the properties if matching properties do not exist
PDO::FETCH_INTOUpdates an existing instance of the named class
PDO::FETCH_LAZYCombines PDO::FETCH_BOTH / PDO::FETCH_OBJ, creating the object variable names as they are used
PDO::FETCH_NUMreturns an array indexed by column number
PDO::FETCH_OBJreturns an anonymous object with property names that correspond to the column names
//set it like this
$statement->setFetchMode(PDO::FETCH_ASSOC);
//FETCH_ASSOC
$statement = $db->query('SELECT title, duration, tracknumber from songs'); //shortcut to fetch when there are no options
$statement->setFetchMode(PDO::FETCH_ASSOC);
while($row = $statement->fetch()) {
  echo $row['title'] . "\n";
  echo $row['duration'] . "\n";
  echo $row['tracknumber'] . "\n";
}
//FETCH_OBJ
$statement = $db->query('SELECT title, duration, tracknumber from songs');
$statement->setFetchMode(PDO::FETCH_OBJ);
while($row = $statement->fetch()) {
  echo $row->title . "\n";
  echo $row->duration . "\n";
  echo $row->tracknumber . "\n";
}

Other Methods

$db->lastInsertId()

returns the last inserted row by that connection

exec()

Used for queries that only return the affected row. Like when you delete

$db->exec('DELETE FROM songs WHERE 1');
quote( )

Quotes strings so they are safe to use in queries, shouldn't be needed if you're using prepared statements.

$new_string = $db->quote($old_string);

rowCount()

Returns the number of rows affected by an operation

$rows_affected = $statement->rowCount();