CSCI.4220 Network Programming
Fall, 2006
Class 19: PHP

This link shows the current popularity of various programming languages.

A server side scripting language (free, open source, platform independent)

PHP stands for PHP hypertext preprocessor

PHP scripting blocks start with <?php and end with ?>.

PHP files contain html with embedded PHP tags

The cout equivalent is echo

Solving the hello world problem in php. Here is helloworld.php

<html>
<body>
<?php
echo ``Hello World'';
?>
</body>
</html>

To run it, put it in your public.html directory with the name helloworld.php Open a browers and point it to
http://cgi2.cs.rpi.edu/~YourLogin/helloworld.php

Note that the domain is cgi2, not www.

If you looked at the source on your browser, you would see this

<html>
<body>

Hello World

</body>
</html>

You can execute this as an ordinary executable with the php command

Variable names start with a dollar sign. Variables can contain strings, numbers or arrays

You can declare constants with the define function

define ("EXCHANGERATE", .79)

To concatenate two or more variables together for echo, use the dot operator

It supports all the usual operators (more or less identical to C)

If else, while, do... while, for, foreach foreach(array as value)
value will assume the value of each element in the array

switch statements

Arrays and other collective data types

You can declare a plain old array (altho it's actually a vector) in the usual fashion

<html>
<body>
<?php
$days=array("Sunday","Monday","Tuesday","Wednesday");
echo $days[2];
echo "<p>Here is a demo of the foreach statement<p>";
foreach($days as $x) {
    echo $x . "<br>";
}
?>
</body>
</html>
The index is an integer starting at zero.

An array in PHP is actually more like a vector because it can be expanded infinitely as needed.

There are lots of built-in array functions. Here are some examples.

You can also have an associative array in which the index is a string.

<html>
<body>

<?php
$capitals["Massachusetts"]="Boston";
$capitals["New York"]="Albany";
$capitals["Vermont"]="Montpelier";
echo "The capital of Vermont is " . $capitals["Vermont"];
?>

</body>
</html>

You can write functions in PHP. Function declarations always start with the keyword function; otherwise they work just like function declarations in any other language.

<html>
<body>

<?php
function Add($x, $y) {
$sum = $x + $y;
return $sum;
}

$a = 17;
$b = 12;
echo "The sum of " . $a . " and " . $b . " is " . Add($a,$b);
?>

</body>
</html>

PHP has thousands of built-in functions Here is a link to all of them.

The phpinfo function shows all of the PHP information

<html>
<body>
<big>
<?php
// Show all PHP information
phpinfo();
?>
</body>

Try it!

You can even write recursive functions.

<html>
<body>
<big>
<b>
<center>
<?php
function recursion($a)
{
   if ($a < 70000) {
       echo $a . "<br>";
       recursion($a * 2);
   }
}

$x = 2;
recursion($x);
?>
</body>
</html>

Try it!

To get the data passed in from a client, use the $_GET or the $_POST variables. These are associative arrays so you access a particular value with the varname in square brackets.

Here is our CurrencyConverter example CurrencyConverter.php

<html>
<head>
<title>CurrencyConverter.php</title>
</head>
<body>
<big>
<?php 
define("RATE",.79);
echo "$ " . $_GET["amount"] . " = &euro;" . $_GET["amount"] * RATE;
?>
</body>
</html>

Here is the front end (client) for it (CurrencyConverter.html).

<html>
  <head>
    <title>Currency Converter</title>
  </head>

  <body>
    <h1>Currency Converter</h1>
    <form method=GET 
       action="http://cgi2.cs.rpi.edu/~ingallsr/CurrencyConverter.php">
    <P>
     converts dollars to euros<p>
     Enter the dollar amount in the box<p>
     <input type=text name="amount"><p>
     <input type="submit"></form>
  </body>
</html>

Try it!

Files use the old fashioned C functions

fopen opens a file
fgets reads a line from the file

<html>
<body>

<?php
$file=fopen("welcome.txt","r");
if (!$file) {
   exit("Unable to open file!");
}
?>

</body>
</html>

PHP can throw exceptions with the try catch syntax.

PHP Server Variables

All servers hold information such as which URL the user came from, what's the user's browser, and other information. This information is stored in variables.

In PHP, the $_SERVER is a reserved variable that contains all server information. The $_SERVER is a global variable - which means that it's available in all scopes of a PHP script. Example

The following example will output which URL the user came from, the user's browser, and the user's IP address:

<html>
<body>

<?php
echo ``Referer: `` . $_SERVER[``HTTP_REFERER''] . ``<br />'';
echo ``Browser: `` . $_SERVER[``HTTP_USER_AGENT''] . ``<br />'';
echo ``User's IP address: `` . $_SERVER[``REMOTE_ADDR''];
?>

</body>
</html>

The header() function is used to send raw HTTP headers over the HTTP protocol.

Note: This function must be called before anything is written to the page!

<?php
//Redirect browser
header(``Location: http://www.w3schools.com/'');
?>

Note: This function also takes a second parameter - an optional value of true or false to determine if the header should replace the previous header. Default is TRUE.

However, if you pass in FALSE as the second argument you can FORCE multiple headers of the same type.

To set a cookie, use the setcookie function

setcookie(name, value, expire, path, domain);

Note that this has to appear before the html tag

<?php 
setcookie("user", "Alex Porter", time()+3600);
?>
<html>
....

To retrieve a cookie value sent from the client, use the variable $_COOKIE. Since this is an associative array, you need to use one of the five fields

PHP sessions

You can get session information with cookies, but php has session functions

<?php session_start(); &>

This creates a global array $_SESSION. This is an associative array so you can set whatever variables you need.

XML Parsing

PHP supports the full XML DOM parser (there are actually three different xml parsers available)

<html>
<body>
<?php

if (!$xmlDoc = domxml_open_file("Plants.xml")) {
     echo "Error parsing the document";
     exit;
}
$root = $xmlDoc->document_element();
echo "Root tag is " . $root->tagname() . "<BR>";
foreach ($root->child_nodes() as $node) {
     if ($node->node_type() == XML_ELEMENT_NODE) {
          echo $node->node_name() . "<br>" ;
     }
}
?>
</body>
</html>

Reading

Read the W3School PHP tutorial