CSE 154

Lecture 16: Intro to PHP

servers

XKCD 869

Agenda

Great work on CP3!

Reminder HW3 Milestone 1 is due Monday

GET vs. POST in AJAX requests

Introduction to PHP!

GET and POST

There are two common ways to make AJAX requests to a server.

  • GET requests are intended to get information from the server (this is the default, most of what you've seen uses GET requests).
  • POST requests are intended to send information to the server, often changing information on the server.

Sending parameters in AJAX with fetch

  • For GET requests, add them to the end of the url:
    "?param1=value1&param2=value2" (same as what you've been doing)
  • For POST requests, create a new FormData() and then use append(key, value) to add key, value pairs. Then include it in the fetch body (here our FormData variable is called params:
let params = new FormData();
params.append("paramName0", "paramValue0");
params.append("paramName1", "paramValue1");
... // any other params

fetch(url, { method : "POST", body : params })
  .then(checkStatus)
  ... // etc.

JS POST request (template)

GET vs. POST Requests: An Analogy

A common analogy is 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)

fetch with GET (default) Code Example

// assume checkStatus() already included
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

fetch with POST Code Example

// assume checkStatus() already included
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

But How Does an Web Service Process our Requests?

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
  • You can explore other server-side languages after this course!

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

Yesterday, you should have installed PHP and a local server through a command line or MAMP. Once you have finished this setup, you're ready to go! When practicing PHP, you can either choose to use the command line or run PHP with localhost.

You can follow along using one of the following two approaches:

  1. Interactive Mode in your command line (similar to JavaScript console)
  2. Writing .php files in your editor (like Atom) and viewing them in the browser them with a local server running

1. Interactive Mode in PHP

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

2. Writing/Running .php Files with Local Servers

There are three ways to start local servers for running PHP web services, depending on your OS and whether you have a command line (note: you need to have installed PHP to use any option, which was part of Lab)

  1. MAMP
  2. Atom
  3. PHP on Bash

Writing/Running .php Files with MAMP Local Server

Remember to start MAMP and:

  • Edit your PHP/other code in C:/MAMP/htdocs on Windows, /Applications/MAMP/htdocs on Mac)
  • Go to http://localhost/ where this code is served by default on Windows, http//localhost:8888/ on Macs

Writing/Running .php Files with php-server package (Atom)

It turns out once you have PHP installed on your computer, you can run a local server directly in Atom! You'll need to install the php-server package (which takes about 20 seconds to install) and use the default localhost settings. Then you can right-click on the php file you're writing and click "Run PHP Server" and the page will open on your default browser!

Video

To stop the server, type Ctrl+Shift+P and type "Php Server: Stop"

Writing/Running .php Files with PHP Local Server (Command Line)

If you have a command line with PHP (Mac or Ubuntu Bash for Windows), you don't need MAMP to start a local server. You can point to your directory of choice and then run the following:

local server on ubuntu windows

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 = "Ethiopian";
echo $favorite_food[2]; # prints "h"

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).

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?)

More PHP Syntax Examples

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

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)

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)

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

NULL

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

PHP

A variable is NULL if

  • It has not been set to any value (undefined)
  • It has been assigned the constant NULL
  • 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)