PHP

PHP is a general purpose programming language that can be used for everything from handling HTML forms, updating and querying a SQL database, data analysis, and general purpose coding tasks. PHP, like any programming language, has its fans and critics. Beyond learning the specifics of this language, we seek to show you the parallels betewen PHP, Javascript, and most modern-day programming languages. One of the benefits of learning more than one language is that it not only provides you more tools in your arsenal, but it also makes it easier to learn other programming languages.

Variables

As with Javasrcipt, we use variables to store information. While conceptually the same, the syntax is slightly different. Here is what you need to know.

With the excpetion of the Resources data types, these data types are the same as in Javascript (and most other modern programming languages).

Examples

Here is a simple example where we define two variables (x and y) and set their sum to the variable z. As with Javascript, you should end each statement with a semicolon (;). The print statement, of course, prints the value in the variable z (50).

<?php

$x = 42;
$y = 8;
$z = $x + $y;
print( "$z" );

?>

Here is an example were we defined two variables (x and y) of type string – notice the double quotes around the strings. The variable z is the string concatentation (the . operator) of these two variables. The print statement then prints “Hello, my name is Hany Farid”. {.php}

PHP offers a different type of variable, a constant. Once defined, a constant cannot chanage during the execution of your code. Although not required, by convention, constants are named using all capital letters – this provides a convenient way of highlighting the use of constants anywhere in the code.

We use the define() function to define a constant. For eample, in the code below, we have defined the constant MAXVAL to be 100. Notice that unlike variables, the constant name is not prefixed with $.

<?php
   define("MAXVAL", 100);
?>

We can now use this constant as we would a variable. For example, this code snippet adds 10 to MAXVAL and prints the resulting variable x:

<?php
   define("MAXVAL", 100);
   $x = 10 + MAXVAL;
   print( "$x" );
?>

You can also use the constant() function to directly access the value of a constant:

<?php
   define("MAXVAL", 100);
   print( constant("MAXVAL") );
?>

Operators

PHP provides the usual arithmatic operators: * Addition (+), 1 + 1 yields 2 * Subtraction (-), 1 - 1 yields 0 * Multiplication (), 2 2 yields 4 * Division (/), 2 / 2 yields 1 * Modulus (%), x % y yields the remainder of diving x by y * Increment (++), x++ adds one to the value of x * Decrement (–), x– subtracts one from the value of x

The comparison operators supported by PHP are: * Equality (==), x == y returns True if the values of x and y are the same (note that in Javascript equality is specied with a triple equal sign (===)) * Not equality (!=), x != y returns True if the values of x and y are not the same * Greater than (>), x > y returns True if the value of x is greater than the value of y * Less than (<), x < y returns True if the value of x is less than the value of y * Greater than or equal (>=), x > y returns True if the value of x is greater than or equal to the value of y * Less than or equal (<=), x < y returns True if the value of x is less than or equal to the value of y

The assignment operators supported by PHP are: * Assignment (=), x = x + 1 assigns to the variable x the result of evaluating the right hand side of the expression * Addition and Assignment (+=), x += 1 is equivalent to x = x + 1 (as well as x++). This notation is also supported by subtraction (-=), multiplication (*=), division (/=), and modulus (%=)

The logical operators supported by PHP are: * And, A and B evaluates to True if both the operands (A,B) are True, and evaluates to False otherwise * Or,A or B evalues to True if either of the operands (A,B) are True, and evaluates to False otherwise * Not, !A evalues to True if the operand (A) is False, and evaluates to False if the operand is True

Conditionals

At this point you will have noticed that PHP offers the same basic constructs as Javascript with only a few minor syntactic differences. This trend continues with respect to control the flow of executing with conditionals and loops.

The basic syntax for a conditional is:

<?php

if( condition )
   code to be executed if condition is true;
else
   code to be executed if condition is false;

?>

As with Javascript, the else clause is optional and you can include zero or more elseif clauses:

<?php

if( condition1 )
   code to be executed if condition1 is true;
elseif( condition2 )
   code to be executed if condition1 is false and condition2 is true;
else
   code to be executed if condition1 is false and condition2 is false;

?>

Because a single conditional with a single else clause is so common, PHP also offers a particularly concise syntax for such expression. This conditional, for example, will print “x is odd” because the variable x is odd:

<?php

$x = 3;
if( $x % 2 == 0 )
    print( "x is even" );
else
    print( "x is odd" );
?>

This if-else clause can be written as a single line using the ?: syntax:

<?php

$x = 3;
$x % 2 == 0 ? print( "x is even" ) : print( "x is odd" );

?>

If the condition to the left of the question mark (?) evaluates then the expression between the question mark and colon (:) is evaluated, otherwise, the expression after the colon is evaluated. This syntax is simply a concise, and identical, version of the if-else clause (and it tells those reading your code that you a serious programmer).

Loops

There are four basic looping mechanisms in PHP. Each of these mechanisms perform the same basic function – repeatedly evaluate one or more lines of code for some fixed number of iterations or until some condition no longer holds. We will describe the for-loop and while-loop next, and the foreach-loop later in this lecture (the fourth, the do… while loop is a variant of a while-loop and for the sake of brevity we won’t descirbe it).

For

The basic structure of a for loop consists of a header and a body. The header specfies the initialization of a variable (the loop counter), the condition(s) under which the loop should continue to evaluate (typically as long as the loop counter is less than or greater than some value), and the manner in which the loop counter should be incremented (or decremented) on each iteration of the loop. The body, enclosed between an open and closed curly bracket, consists of one or more lines of code that are executed on each iteration of the loop.

for( initialization; condition; increment ) { 
     code to be executed;
}

This simpele for-loop, for example,

<?php

for( $i = 0; $i<10; $i++ ) { 
     print( "$i " );
}
print( "\ndone\n" );

?>

This for loop initializes the variable i to 0, increments this variable by one on each iteration of the loop (i++) and continually executes the body of the for-loop (a single print statement) until i is less than 10. Be careful when setting these conditions to make sure that you do not end up with the classic off-by-one bug (i.e., should the stopping condition be i<10 or i<=10 – in this case, we only wanted to print 0 through 9, so i<10 (or i<=9) is correct). The output of this code snippet is:

0 1 2 3 4 5 6 7 8 9 
done

Note that because there is no carriage return (\n) in the print statement executed on each iteration of the loop, the numbers 0 to 9 are printed on the same line. The final print statement, outside of the for-loop, prints a carriage return first so that done is printed on a separate line. Note also that the variable i continues to have a value after the for-loop has finished executing. That is, if we had printed the value of i after the printing of done, we would see that this variable has a value of 9.

While

Like a for-loop, the basic structure of a while loop consists of a header and a body. The header specfies the condition(s) under which the loop should continue to evaluate. The body, enclosed between an open and closed curly bracket, consists of one or more lines of code that are executed on each iteration of the loop.

while (condition) { 
     code to be executed;
}

The while-loop below generates exactly the same output as the for-loop above. Notice that the same basic components are present in both loops: initialization ($i=0, condition ($i < 10), increment ($i++), and a body (print). The only difference is that the first three of these are bundled up into the header of the for-loop as compared to the while loop in which only the condition is contained in the header and the initialization is done outside of the loop and the increment is done (of course) inside of the loop.

<?php

$i = 0;
while( $i < 10 ) {
     print( "$i " );
     $i++;
}
print( "\ndone\n" );

?>

You may wonder why we need two seperate and identical structures. Although in this example, the for- and while-loop are identical, the primary difference between a for- and while-loop is that a for-loop will always run for a finite number of iterations whereas a while-loop can be constructed to run for an infinite number of iterations. For example, this while-loop in which we simply removed the increment, the loop will never stop unless its executiion is interrupted by an external force (you run out of battery).

<?php

$i = 0;
while( $i < 10 ) {
     print( "$i " );
}

?>

Left to their own devices, a loop will execute the code in its body until the specified condition(s) are no longer true. There are two mechanism for disrupting this execution: continue and break. The continue command halts the current iteration of a loop while the break command halts the loop entirely. For example, in this code snippet, the recipriocal of every integer between -5 and 5 will be printed, except for 1/0. When the value of i is 0, the conditional inside of the for-loop evaluates to True and the continue command tells PHP to skip the rest of the body of the for-loop and continue on to the next iteration.

<?php

for( $i=-5; $i<=5; $i++ ) {
     if( $i == 0 )
          continue;
     print( "1/$i\n" );
}

?>

In contrast, in this code snippet, the recipriocal of every intger between -5 and -1 will be printed. When the value of i is 0, the conditional inside of the for-looop evaluates to True and the break command tells PHP to exit the while loop entirely.

<?php

for( $i=-5; $i<=5; $i++ ) {
     if( $i == 0 )
          break;
     print( "1/$i\n" );
}

?>

The continue and break commands can be used in a for- or while-loop and are useful for catching specific cases that obviate the need for continuing a loop. For example, if we were searching the contents of an array (see below) for an even number we would iterate over all entries in the array and could exit the loop as soon as we found an even number.

Arrays & Associative Arrays (Dictionaries)

PHP, like Javascript, provides an array data structure. The standard array, referred in PHP as a numeric array, stores one or more data values in a single data structure.

An array is initialized with the array() command. For example, in the code below A is first initialized as an array and then three values (the string “one”, “two”, and “three”) are assigned. Note that like all variables in PHP, the variable A is prefixed with a $. And, like Javascript, arrays are indexed starting at 0, not 1.

<?php

$A = array();

$A[0] = "one";
$A[1] = "two";
$A[2] = "three";

?>

There are two primary ways in which we can enumerate the elements of an array. We can use a for-loop to, for example, print the elements of an element. In this for loop, the loop counter i takes on the values 0, 1, 2 corresponding to each element of the array A.

<?php

$A = array();

$A[0] = "one";
$A[1] = "two";
$A[2] = "three";

for( $i=0 ; $i<=2 ; $i++ ) {
  print( "$A[$i]\n" );
}

?>

Hard-coding the length of the array in the for-loop is a bad idea because if the length of the array changes, then we will have to make sure to remember to update the value of the loop’s stopping condition – not doing so will lead to an error or bug in the code. Instead of hard-coding the length, we can ask PHP for the length of the array using the sizeof command, yielding the following for-loop: for( $i=0 ; $i<sizeof($A) ; $i++ ).

Alternatively, and equivalently, to the above for-loop, PHP provides a “foreach” looping construct that automatically enumerates all elements of an array. In the code below, instead of specifying the values of a counter in a traditional for-loop, we simply specify the array we’d like to enumerate over (A) and the name of a variable that will take on the value of each element of the array (a). This variable a is equivalent to $A[$i] in the above for-loop.

<?php

foreach( $A as $a ) {
  print( "$a\n");
}

?>

A standard array, sometimes referred to as a numeric array, is indexed using the integer values 0, 1, 2, … An associate array, sometimes referred to as a dictionary, can be indexed on strings. For example, the array B in the code below is indexed on the strings “one”, “two”, and “three”. As with a numeric array, the values stored in these array elements can be anything – here they are simply integer values.

And, as with numeric arrays, we can use the foreach construct to enumerate overall all elements in an associative array.

<?php

$B = array();
$B["one"] = 1;
$B["two"] = 2;
$B["three]"] = 3;


foreach( $B as $b ) {
  print( "$b\n");
}

?>

Functions

At this point, we have reveiewed the major building blocks for PHP. As we have previously learned, one of the most important concepts in coding is the notion of abstraction – bundling up functionality in a single function so that we can use our own or someone else’s functions to solve increasingly more complex problems. To do this, we need to be able to define functions.

Each function definition starts with the keyword function followed by the name of your fucntion (myAdd in the example below), followed by open and close parantheses() inside of which we can optionally specify variables that can be passed as input to the function, followed by an open curly bracket {. The body of the function is one or more lines of valid PHP code and finally, the function ends with a close curly bracket }.

<?php

function myAdd( $a, $b ) {
  $s = $a + $b;
  print( "$s" );
}

?>

Our newly defined function can be called as follows: myAdd(1,2). The variables a and b will be assigned to the values 1 and 2, respectively, and then the variable s will be assigned the sum of these values and finally the value 3 will be printed.

Functions, in addition to taking input can also return values (don’t confuse returning with printing – the function above prints, the function below returns). In the function below, the return statement simply returns to the calling function the value of s. The caller is then responsible for what to do with that value. In the example below, the returned sum is assigned to a new variable x.

<?php

function myAdd( $a, $b ) {
  $s = $a + $b;
  return( $s );
}

$x = myAdd( 1, 2 );

?>

Client Information

We have shown how to request, send, extract, and store user-supplied data. In addition to this data, you can extract some information directly from the client without explicitly requesting it from the user. Similar to the _POST[...] variable used for extracting data from the client-side form, PHP provides a _SERVER[...] variable from which we can extract information about the client. This includes such things as the type of client browser and operating system, the client IP address, the URL of the page (if nay) which referred the user to your page, and the date/time in the client’s timezone.

<?php

$agent    = $_SERVER['HTTP_USER_AGENT'];
$ip       = $_SERVER['HTTP_CLIENT_IP'];
$referrer = $_SERVER['HTTP_REFERER'];
$time     = $_SERVER['REQUEST_TIME'];

?>

The misspelling of referer (HTTP_REFERER) dates back to the original proposal for incorporating this information into the HTTP specification. By the time that the spelling mistake was noticed, it was in such wide use that changing it was impractical.

Cookies

Cookies are used as a way for you to keep track of a user through multiple visits to your website. Cookies are small pieces of information stored on the client’s computer. All–not just your cookies–are sent by the client’s browser to the server with every form submission. PHP provides a mechanism for creating, reading, updating, and deleting cookies.

The PHP command setcookie is used to set a cookie. This requires you to supply three pieces of information: a string containing the name of the cookie (usually something related to the name of your site; a string containing the value of the cookie (this is the data that you want to store on the client’s browser for future access); and a time (in seconds) for when the cookie expires. In the code snippet below, the name is “FWP”, the value is a variable that might hold the user’s name, and the expiration date is 30 days (30 * 24 hours/day * 60 minutes/hour * 60 second/minute).

<?php
setcookie( "FWP", $username, time() + (30*24*60*60) );
?>

Similar to the _POST[...] and _SERVER[...] variables, PHP provides a _COOKIE[...] variable for accessing the contents of a cookie. This code snippet assigns to the variable cookie the value of the cookie associated with the name “FWP”.

<?php
$cookie = $_COOKIE["FWP"];
?>

And lastly, you can delete a cookie by simply settting the expiration to a point in the past:

<?php
setcookie( "FWP", $username, time()-1 );
?>

Sessions

Sessions are an alternative way to keep track of a user as they navigate your website during a single or multiple visits. Unlike cookies that store information on the client’s browser, sessions store information on the server. We will not go into more detail here, but we encourage you to read up on this alternative way of keeping track of a user as they navigate your site.