CSE 154

Lecture 17: Intro to PHP

servers

XKCD 869

Administrivia

HW3 due Monday

Introduction to Module 4 and PHP!

Review: Web Services

Web service: software functionality that can be invoked through the internet using common protocols

It's like a remote function(s) you can call. Done by contacting a program on a web server

  • Web services can be written in a variety of languages
  • Many web services accept parameters and produce results
  • Client contact the servier through the browser using XML over HTTP and/or AJAX Fetch code
  • The service's output might be HTML but could be text, XML, JSON, or other content

Some Web Services We've Used as Clients

Merriam-Webster Dictionary API

NASA APOD API

CSE154 web services:

  • groupizer.php
  • pizza.php
  • pokedex.php and game.php
  • wpl.php
  • mowgliscafe.php

Wednesday's WPL Example

Used to show a few input validation methods before sending a request to the wpl.php web service.

WPL example

Sending a Request

Once we've validated the input a bit, the request is sent and we recieve a response from wpl.php

WPL example

Motivating the Client-Server Relationship

We've used the analogy of a customer (client) ordering from a waiter at a restaurant (server). In this analogy, what might a customer ask for from "GET" request? What might a "POST" request be?

get/post image

Image source (a wonderful reading to explain front-end vs. back-end/server relationships)

Client (JS) GET Request

function requestMenu() {
  let url = RESTAURANT_URL;
  url += "?menu=all";

  //fetch by default is a GET request
  fetch(url)
    .then(checkStatus)
    .then(JSON.parse)
    .then(handleResponse)
    .catch(handleError);
}

JS

Client (JS) POST Request

function sendOrder() {
  let url = RESTAURANT_URL;

  let params =  new FormData();
  params.append("name", "Mowgli");
  params.append("order", "coffee");
  params.append("qty", 154);

  fetch(url, {method: "POST", body: params})
    .then(checkStatus)
    .then(JSON.parse)
    .then(handleResponse)
    .catch(handleError);
}

JS

How Does a Web Service (like wpl.php or cafe.php) Respond to Requests?

full stack analogy

Image source

CSE 154 Modules: Where We're At

  1. Webpage structure and appearance with HTML5 and CSS.
  2. Client-side interactivity with JS DOM and events.
  3. Using web services (API's) as a client with JS.
  4. Writing JSON-based web services with PHP.
  5. Storing and retreiving information in a database with MySQL and server-side programs.

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

Why Do We Need a Server to Handle Web Service Requests?

server analogy

Servers are dedicated computers for processing data efficiently and delegating requests sent from many clients (often at once).

Thinking back to the restaurant transaction analogy, what kind of information:

  1. should be accessible to clients to freely request ("GET")?
  2. might be useful for a client to update ("POST") on the server?
  3. might need to be kept private on the server?

Languages for Server-Side Programming

server side languages

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

Web servers (including those you setup yesterday) contain software to run those programs and send back their output.

PHP: Our Server-Side Language

  • Open-source
  • Widely supported
  • Few dependencies (already ready-to-go with MAMP!)
  • You can explore other server-side languages after this course!

Lifecycle of a PHP Web Request

PHP web request lifecycle

When a browser requests:

  • a .html file (static content): server just sends that file
  • a .php file (dynamic content): server reads it, runs any script code inside it, then returns the output (possibly as JSON/text/HTML)

Note: We will be using PHP to write web services, not embedding it in HTML - you will see this still in some online resources (what do you think are limitations to embedding PHP in HTML, knowing what we've learned so far?)

JS vs. PHP

JS PHP
Language Type Client-side Scripting Server-side Scripting
File Extension .js .php
Code Execution Web Browser Web Server
Access to File System No Yes
Access to Database No Yes

Getting started with PHP

You will have PHP installed already with your MAMP local server So you should be ready to go!

When practicing PHP, you can also find it useful to play around with the interactive PHP mode on a the command line, which is analogous to the Chrome JS console (see slide below).

Handy Interactive Mode in PHP (Command Line)

When first learning the syntax of PHP, it can be helpful to use an "interactive environment", which is very similar to the interactive JavaScript console we've used. You can start an interactive coding session using php -a:

Interactive PHP

Writing/Running .php Files with MAMP

Editing PHP: Atom (just like you've been doing already)

Running/viewing PHP: You can view the output of a .php program in the browser (through localhost) - MAMP must be running!

  • Remember to edit your PHP/other code in the folder MAMP points to so you can run them through locahost:
    • Mac: localhost:8888/php-practice.php
    • Windows: localhost/php-practice.php

You can also fetch the output with a request to your PHP program the same way you've done with other web services as a client (more next week)!

The PHP file skeleton

PHP files must start with <?php an end with ?>. It is common to forget these when you're first starting PHP, so make sure to start each file with them! Anything PHP statements inside will be executed when the program is ran.

running php

The Basics of PHP

Now that we've got a way to run PHP code, let's get started with the basics!

We've provided a php-examples.php program in php-examples.zip with examples for variables/types/functions in PHP - try uncommenting the different statements and changing them to practice with the new syntax! We'll get through Strings today but will review the rest of the examples (arrays, if/else, loops, and functions) on Monday.

Console Output: print/echo

There are two ways to print in PHP (you may use either, as long as you're consistent):

print "text";
echo "text"; 

PHP (template)

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

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

PHP (example)

The following two slides demonstrate this program in both interactive mode and running the program. Try both out on your own!

Console Output: Interactive Mode

Console Output: Running console-output.php

Note: By default, your PHP will output to the body of the HTML page (check the inspector!). Since we aren't using PHP to output HTML, we will often use header("Content-type: text/plain"); at the top of our PHP program to output plain text (otherwise we won't get the \n character in our output in this example)

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

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 = "coffee!";
echo $favorite_food[2]; # prints "o"

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"

Seriously. You will make this mistake at least once. It's ok :) just add it to your list of "common PHP bugs" (yes, you might want to start a list).

More PHP Syntax Examples

(Will review for first part of Monday, but included for practice over the weekend

String Functions

# index  012345678901
$name = "Mowgli Hovik";
$length = strlen($name);                # 12
$index_of_h = strpos($name, "H");       # 7
$last = substr($name, 7, 12);           # "Hovik"
$name = strtoupper($name);              # "MOWGLI HOVIK"

PHP

Name Java Equivalent
strlen($str) str.length
strpos($str, $ch) str.indexOf(ch)
substr($str, $start, $end) str.substring(start, end)
strtolower($str), strtoupper($str) str.toLowerCase, str.toUpperCase
trim($str) str.trim()
explode($delim, $str), implode($delim, $arr) str.split(delim), String.join(delim, values)

See slides below for Java and Python equivalents!

PHP vs. Java Strings

# index  012345678901
$name = "Mowgli Hovik";
$length = strlen($name);                # 12
$index_of_h = strpos($name, "H");       # 7
$last = substr($name, 7, 12);           # "Hovik"
$name = strtoupper($name);              # "MOWGLI HOVIK"

PHP

# index  012345678901
String name = "Mowgli Hovik";
int length = strlen($name);             # 12
int indexOfH = name.indexOf("H");       # 7
String last = name.substring(7, 12);    # "Hovik"
name = name.toUpperCase();              # "MOWGLI HOVIK"

Java

Interpreted Strings

$age = 16;
echo "You are " . $age . " years old.\n";
echo "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:

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

PHP

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

echo "Today is your $ageth birthday.\n"; # ageth not found
echo "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

PHP has similar "truthy/falsy" properties as JS (more details)

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

FALSE prints as an empty string (no output); TRUE prints as a 1 (why do you think that is?)

For Loops

      for (initialization; condition; update) {
  statements
}

PHP (template)

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

PHP (example)

(remember . not + for string concatenation)

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)

Functions

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

PHP (template)

function calculate_profit($cost, $price, $qty) {
  return ($price / $cost) * $qty;
}

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)

$qty = 154; # quantity
$bagel_price = 0.85; # A plain bagel costs .85 to make!
$bagel_sell  = 3.50; # A plain bagel sells for 3.50!
$profit = calculate_profit($bagel_cost, $bagel_price, $qty);
# Who needs a degree when you can sell bagels?

PHP (example)

Practice

Write a function named repeat that accepts a string and a number of repetitions as parameters and returns the string concatenated that many times.

For example, the call of repeat("hello", 3) returns "hellohellohello". If the number of repetitions is 0 or less, return an empty string.

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)

            $pups = array ("Mowgli", "Abby", "Archie", "Pascal");
foreach ($pups as $pup) {
  echo "Mowgli boops $pup\n"; # even himself
}

PHP (example)