CSE 154

Lecture 17: Intro to PHP

servers

XKCD 869

Administrivia

Cloud 9 - email sent Tuesday

Exploration session Thursday, 5:30pm, MGH 241

Reading API Documentation (for CP5)

Setting context

Review: What This Class is About (on the surface)

The Internet

An overview of how the Internet works

How to make web pages

How to make web pages interactive

Review: What You Will Really Do:

Learn five languages in ten weeks

Develop client- and server-side programs

Practice the skill of following detailed but seemingly vague specifications

Search for appropriate solutions

Build a portfolio to show!

Review: Course outline

✔ HTML: Webpage content

✔ CSS: Webpage presentation

✔ JavaScript: Webpage functionality (client-side)

- AJAX: Fetching data from the internet

- JSON: JavaScript Object Notation for parsing data nicely


PHP: Server-side code with PHP

Sending JSON formatted data

Regular Expressions: Validating input

SQL: Storing data

Review: URLs and Web Servers

https://server/path/file

Usually when you type a URL in your browser:

  1. Your computer looks up the server's IP address using DNS
  2. Your browser connects to that IP address and requests the given file
  3. The web server software (e.g. Apache) grabs that file from the server's local file system and then send back its contents to you

Some URLs actually specify programs that the web server should run, and then send their output back to you as the result:

https://webster.cs.washington.edu/cse154/quote.php

The above URL tells the server webster.cs.washington.edu to run the program quote.php and send back its output

Server-Side Programming

server side languages

Server-side programs are written using programming languages/frameworks such as:

Web servers contains software to run those programs and send back their output

Each language/framework has its pros and cons

Popularity of languages/frameworks can change quickly:

We will use PHP for server-side programming

Lifecycle of a PHP Web Request

PHP web request lifecycle

Browser requests a .html file (static content): server just sends that file

Browser requests a .php file (dynamic content): server reads it, runs any script code inside it, then returns the output

Console Output: print

      
print "text";
echo "text"; 

PHP (template)


print "Hello, World!\n";
print "Escape \"chars\" are the SAME as in Java!\n";
print "you can have
line breaks in a string.";

print 'A string can use "single-quotes". It\'s cool!';

PHP (example)

Hello, world!
Escape "chars" are the SAME as in Java!
You can have line breaks in a string. A string can use "single-quotes". It's cool!

output

Some PHP programmers use the equivalent* echo instead of print

PHP file skeleton

<?php
  //PHP code goes here
  echo "This is a test!";
?>

output

This is a test!

output

Arithmetic Operations

+ - * / %
. ++ --
= += -= *= /= %= .=

Many operators auto-convert types: 5 + "7" is 12

Variables


$name = expression;
          

PHP (template)


$user_name = "Pokemon4Lyfe";
$age = 25;
$age_in_dog_years = $age / 7;
$this_class_rocks = TRUE;
          

PHP (example)

Names are case-sensitive; separate multiple words with _ (as in $user_name)

Names always begin with $ on both declaration and usage

Implicitly declared by assignment (type is not written; a "loosely-typed" language)

Types

Basic types: integer , float , boolean , string , array , object , NULL

Test what type a variable is with is_type functions, e.g. is_string

gettype function returns a variable's type as a string (not often needed)

PHP converts between types automatically in many cases:

  • string to int auto-conversion on + for ("1" + 1 == 2)
  • int to float auto-conversion on / for (3 / 2 == 1.5)

Type-cast with (type):

  • $age = (int) "21";

String Type

Can be specified with "" or ''


      $favorite_food = "Ethiopian";
      print $favorite_food[2];
          

PHP

0-based indexing using [] bracket notation

String Concatenation

Important note! String concatenation is . (period) not +

  • 5 + "2 turtle doves" produces 7
  • 5 . "2 turtle doves" produces "52 turtle doves"

String Functions


# index  0123456789012345
$name = "Wanda Gershwitz";
$length = strlen($name);                # 15
$cmp = strcmp($name, "DD");             # > 0
$index = strpos($name, "r");            # 3
$last = substr($name, 6, 10);           # "Gershwitz"
$name = strtoupper($name);              # "WANDA GERSHWITZ"
          

PHP

Name Java Equivalent
strlen length
strpos indexOf
substr substring
strtolower, strtoupper toLowerCase, toUpperCase
trim trim
explode, implode split, join

Interpreted Strings


      $age = 16;
      print "You are " . $age . " years old.\n";
      print "You are $age years old.\n"; # You are 16 years old.
          

PHP

Strings inside " " are interpreted

  • Variables that appear inside them will have their values inserted into the string

Strings inside ' ' are not interpreted:


      print 'You are $age years old.\n'; # You are $age years old.
          

PHP

If necessary to avoid ambiguity, you can enclose the variable in {}:


      print "Today is your $ageth birthday.\n"; # ageth not found
      print "Today is your {$age}th birthday.\n";
          

PHP

bool (Boolean) Type


$feels_like_summer = FALSE;
$php_is_rad = TRUE;
$student_count = 217;
$nonzero = (bool) $student_count; # TRUE

PHP

The following values are considered to be FALSE (all others are TRUE):

  • 0 and 0.0
  • "", "0", and NULL (includes unset variables)
  • arrays with 0 elements

Can cast to boolean using (bool)

FALSE prints as an empty string (no output); TRUE prints as a 1

Boolean Operators


$is_warm = TRUE;
$is_rainy = TRUE;
$is_sunny = FALSE;
$summer = $is_warm && $is_sunny;   # FALSE
$winter = $is_rainy || !$is_warm;  # TRUE
$fall = $is_sunny || $is_rainy;    # TRUE

PHP

Boolean operators && and || work the same way as in Java or JavaScript

PHP also has and and or has different precedence rules.

NULL


          $name = "Pascal";
          $name = NULL;
          if (isset($name)) {
            print "This line isn't going to be printed";
          }
            

PHP

A variable is NULL if

  • It has been assigned the constant NULL
  • It has not been set to any value yet (undefined)
  • It has been deleted using the unset function

Can test if a variable is NULL using the isset function

NULL prints as an empty string (no output)

isset()


          if (isset($var1)) {
            print ("This line isn't going to be printed");
          }
          $var2 = 12;
          if (isset($var2)) {
            print ("This line WILL be printed");
          }
            

PHP

Use the isset() function to test if a variable is set and not NULL

If a variable is unset(), isset() will return FALSE

For Loops


for (initialization; condition; update) {
  statements
}

PHP (template)

      
for ($i = 0; $i < 10; $i++) {
  print "$i squared is " . $i * $i . "\n";
}

PHP (example)

If/Else Statements


if (condition) {
  statements;
} else if (condition) {
  statements;
} else {
  statements;
}

PHP (template)

Can also use elseif instead of else if

While Loop (same as Java)


while (condition) {
  statements;
}

PHP (template)

      
do {
  statements;
} while (condition);

PHP (template)

break and continue keywords also behave as in Java (do not use these in this course)

Comments


# single-line comment

// single-line comment

/*
multi-line comment
*/

PHP

Like Java, but # is allowed

  • A lot of PHP code uses # comments instead of //
  • We recommend # and will use it in our examples

Arrays


$name = array(); # create
$name = array(value0, value1, ..., valueN);
$name[index] # get element value
$name[index] = value; # set element value
$name[] = value; # append PHP

PHP

$a = array(); # empty array (length 0)
$a[0] = 23; # stores 23 at index 0 (length 1)
$a2 = array("some", "strings", "in", "an", "array");
$a2[] = "Ooh!"; # add string to end (at index 5) 

PHP

  • to append, use bracket notation without specifying an index
  • element type is not specified; can mix types

Associative Arrays

Associative arrays are arrays that use named keys that you assign to them.


$age = array("Spot"=>16, "Whitney"=>16, "Jack"=>12); # create
$age["Mowgli"] = 1;

PHP

$a = array(); # empty array (length 0)
$age["Whitney"] = 17; # stores 17 at the location where "Whitney" is stored

PHP

Array Functions

Function name(s) Description
count number of elements in the array
print_r print array's contents
array_pop, array_push, array_shift, array_unshift using an array as a stack/queue
in_array, array_search, array_reverse sort, rsort, shuffle searching and reordering
array_fill, array_merge, array_intersect, array_diff, array_slice, range creating, filling, filtering
array_sum, array_product, array_unique, array_filter, array_reduce processing elements

Array Function Example


            $tas = array("CA", "MJ", "MG", "SK", "KC", "DH", "JZ");
            for ($i = 0; i < count($tas); $i++) {
              $tas[$i}] = strtolower($tas[$i]);
            } # ("ca", "mj", "mg", "sk", "kc", "dh", "jz")

            $conner = array_shift($tas);   # ("mj", "mg", "sk", "kc", "dh", "jz")
            array_pop($tas);               # ("mj", "mg", "sk", "kc", "dh")
            array_push($tas, "kt");        # ("mj", "mg", "sk", "kc", "dh", "kt")
            array_reverse($tas);           # ("kt", "dh", "kc", "sk", "mg", "mj")
            sort($tas);                    # ("dh", "kc", "kt", "mg", "mj", "sk")
            $ks = array_slice($tas, 2, 3); # ("kt")
            

PHP

The array in PHP replaces many other data structures in Java

  • e.g. list, stack, queue, set, map, ...

The foreach loop

A convenient way to loop over each element of an array without indices

            
            foreach ($array as $variableName) {
              ...
            }
            

PHP (template)

            
            $stooges = array ("Larray", "Moe", "Curly", "Shemp");
            foreach ($stooges as $stooge) {
              print "Moe slaps $stooge\n"; # even himself
            }
            

PHP (example)

Functions


function name(parameterName, ..., parameterName) {
  statements;
}
          

PHP (template)


function bmi($weight, $height) {
  $result = 703 * $weight / $height / $height;
  return $result;
}
          

PHP (example)

  • parameter types and return types are not written
  • a function with no return statements is implicitly "void"

Calling Functions

name(expression, ..., expression); 

PHP (template)


$w = 163; # pounds
$h = 70; # inches
$my_bmi = bmi($w, $h);
          

PHP (example)

  • If the wrong number of parameters are passed, it's an error

Default Parameter Values


          function name(parameterName=value, ..., parameterName=value) {
            statements;
          }
            

PHP (template)


          function print_separated($str, $separator=", ") {
            if (strlen($str) < 0) {
              print $str[0];
              for ($i = 1; $i < strlen($str); $i++) {
                print $separator . $str[$i];
              }
            }
          }
          print_separated("hello"); # h, e, l, l, o
          print_separated("hello", "-"); # h-e-l-l-o
            

PHP (example)

If no value is passed, the default will be used (defaults must come last)

Summary of Java vs. JS vs. Python vs PHP

Java JS Python PHP
Compiled vs. Interpreted Compiled Interpreted Interpreted Interpreted
Typing Strong Loose Loose Loose
Variable Declaration Must be declared before use Does not need to be declared before use Does not need to be declared before use Does not need to be declared before use
Key Construct Classes (OOP) Function Function Function

Odds and Ends

PHP Error mode


error_reporting(E_ALL);
          

PHP

This command makes PHP report more errors (sort of like "e;use strict"e; in javascript).

Cloud9 does not have the strict error checking on by deafult.

PHP include


include("otherPhpFile.php");
          

PHP

include runs code from another php file. It works the same as if you just copied the code from the other file and pasted it where the include was.

Variable scope: global


          $school = "UW";               # global
          ...

          function downgrade() {
            global $school;
            $suffix = "(Wisconsin)";    # local

            $school = "$school $suffix";
            print "$school\n";
          }
            

PHP

Variables declared in a function are local to that function; others are global

If a function wants to use a global variable, it must have a global statement

  • but don't abuse this; mostly you should use parameters