0 PHP Introduction

This session provides an overview of important PHP structures and functions. It is not necessary to learn all existing PHP functions. It is preferable to learn a subset of functions (as provided on this website) that can do most things and then to look up additional functions as needed in the PHP manual.

0.1 Setting up PHP files on the server

In general, you need two directories: "public_html" and a subdirectory of "public_html" called "php". The public_html and the php directory should both be world readable and executable. You may also need to change the permissions for your top level directory. The following commands create the directories and set the permissions in a typical Unix environment. On Windows in a WAMP-like environment, the permissions are most likely automatically set at the time of installation.

cd; chmod 711 .;
mkdir public_html; chmod 755 public_html;
cd public_html; mkdir php; chmod 755 php;

All php files should be in the php directory and should have an extension ".php". The URL for PHP files should be something like:
http://someserver/~yourusername/php/filename.php

1 A first example "Hello World"

<html>
<head><title>Hello World</title></head> <body>
<?php
echo "Hello World";
?>
</body></html>

1.1 Exercises

1) Save this PHP script in your php directory under the name helloworld.php. (On Unix you may need to change the permissions, for example: chmod 755 helloworld.php.) Look at the file through your browser.

2) Add a second echo statement to the script from the example. (For example: echo "How are you?".)

3) Make some random changes, for example, delete one of the double quotes. In most cases you will get an error message. The most useful piece of information in that message is probably the number of the line in which the error occurred. Fix the errors until the script executes again successfully.

2 A second example

<html>
<head><title>Hello World</title></head> <body>
<?php
echo "What is your name? ";
echo "Hello, {$_REQUEST['name']}! How are you?";
?>
</body></html>

The variable $_REQUEST['name'] retrieves data from a user request (such as a web form). For testing purposes it can be used via the query string (see next exercise). If you don't like the complicated variable name, write $name = $_REQUEST['name'] at the beginning of the PHP code and then use $name in the rest of the code.

2.1 Exercises

4) Look at the script through your browser. Then add "?name=Snoopy" at the end of the URL:

thenameofyourfile.php?name=Snoopy

and press enter.

5) Write a program that asks two people for their names; stores the names in variables called $_REQUEST['name1'] and $_REQUEST['name2'] and says hello to both of them. (In the URL, you need to separate the variables with "&": "?name1=Snoopy&name2=Charlie".)

3 Operators for Numbers

$a = 3 -4 +10;
$b = 5*6;
$c = 7/8;
echo "These are the values: $a $b $c <br>";
echo "Increment $a by one: ";
$a++;
echo $a;
echo "<br>";
echo "Decrease $a by one: ";
$a--;
echo $a;
echo "<br>";

3.1 Exercise

6) Add the code to your script and see what it does.

3.2 Example

$can_money = $_REQUEST['us_money'] /0.6;
echo "US\$ {$_REQUEST['us_money']} = Canadian \$ $can_money<br>";

3.3 Exercise

7) In analogy to the example, write a script that takes a temperature in F and echos the temperature in C. (Conversion: Celsius = (F - 32) * 5/9 )

4 Logical expressions and control structures

echo "Do you like PHP? <br>";
if ($_REQUEST['answer'] == "yes"){
      echo "That is great!";
} else {
      echo "That is disappointing!";
}

4.1 Exercise

8) Modify the program so that it answers "That is great!" if the answer was "yes", "That is disappointing" if the answer was "no" and "That is not an answer to my question." otherwise. Use "if ... else if ... else ...". Note that "if" and "else if" are followed by an expression in parenthesis () and then a statement in curly brackets {}, "else" is followed only by a statement in curly brackets.

4.2 For loops

An example of a control structures is "for".

for ($i =1; $i <= 10; $i++){
      echo "$i ";
}

The PHP manual has a complete listing of PHP's control structures.

4.3 Exercise

9) Create a script that adds the numbers from 1 to 20 and prints the result. Use a for loop.

5 Arrays

Arrays in PHP are ordered maps (also called "hashs", "associative arrays", "maps", "lookup tables" or "dictionaries" in other programming languages).

$zoo = array("monkey", "tiger", "eagle");
echo "The zoo has the following ".count($zoo)." animals: ";
echo implode (" ",$zoo);
echo ".<br>";
echo "Which animal would you like to add?<br> ";
$new_animal = $_REQUEST['animal'];
array_push($zoo, $new_animal);
echo "The zoo now has the following ".count($zoo)." animals: ";
echo implode (" ",$zoo);
echo ".<br>";
echo "The 3rd animal in the array is $zoo[2].";

5.1 Exercise

10) Create an array that contains the names of 5 students of this class. (You don't need a loop to do that. Simply assign the 5 values.) Echo the array. Remove (array_pop) the last name from the array. Echo the array. Add (array_push) a further name to the array. Echo the array. Echo the array in alphabetical and in reverse order (using sort and rsort).

5.2 Foreach

$zoo = array("tiger", "elephant", "monkey");
foreach ($zoo as $animal) {
    $animal = "_".$animal."_";
    echo "$animal";
}
echo "<br>";

5.3 Exercise

11) Use the array of student names from exercise 10. Create a foreach loop that echos for each student "hello $student, how are you?".

6 Input from a file

Click here and save the file in your PHP directory under the name "alice.txt".

$lines = file('alice.txt');
foreach ($lines as $line_num => $line) {
  echo "Line ",$line_num,": ",$line, "<br>\n";
}

6.1 Exercise

12) Modify the program so that the lines are echoed in reverse order.