HW3 due Monday
Introduction to Module 4 and PHP!
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
Merriam-Webster Dictionary API
NASA APOD API
CSE154 web services:
Used to show a few input validation methods before sending
a request to the wpl.php
web service.
Once we've validated the input a bit, the request is sent and we recieve a response from
wpl.php
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?
Image source (a wonderful reading to explain front-end vs. back-end/server relationships)
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);
}
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);
}
https://server/path/file
Usually when you type a URL in your browser:
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
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:
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.
When a browser requests:
.html
file (static content): server
just sends that file.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 | 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 |
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).
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
:
.php
Files with MAMPEditing 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!
localhost:8888/php-practice.php
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)!
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.
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.
print
/echo
There are two ways to print in PHP (you may use either, as long as you're consistent):
print "text";
echo "text";
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!';
The following two slides demonstrate this program in both interactive mode and running the program. Try both out on your own!
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)
# single-line comment
// single-line comment
/*
* multi-line
* comment
*/
Like Java, but #
is allowed
#
comments instead of //
#
and will use it in our examples
+ - * / %
. ++ --
= += -= *= /= %= .=
Many operators auto-convert types: 5 + "7"
is 12
$name = expression;
$user_name = "Pokemon4Lyfe";
$age = 25;
$age_in_dog_years = $age / 7;
$this_class_rocks = true;
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)
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";
Can be specified with "" or ''
$favorite_food = "coffee!";
echo $favorite_food[2]; # prints "o"
0-based indexing using []
bracket notation
Important note! String concatenation is .
(period) not +
5 + "2 turtle doves"
produces 75 . "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).
(Will review for first part of Monday, but included for practice over the weekend
# 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"
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!
# 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"
# 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"
$age = 16;
echo "You are " . $age . " years old.\n";
echo "You are $age years old.\n"; # You are 16 years old.
Strings inside " "
are interpreted
Strings inside ' '
are not interpreted:
echo 'You are $age years old.\n'; # You are $age years old.
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";
bool
(Boolean) Type$feels_like_summer = FALSE;
$php_is_rad = TRUE;
$student_count = 217;
$nonzero = (bool) $student_count; # TRUE
PHP has similar "truthy/falsy" properties as JS (more details)
The following values are considered to be FALSE
(all others are
TRUE
):
NULL
(includes unset variables)FALSE
prints as an empty string (no output); TRUE
prints as
a 1 (why do you think that is?)
for (initialization; condition; update) {
statements
}
for ($i = 0; $i < 10; $i++) {
print "$i squared is " . $i * $i . "\n";
}
(remember . not + for string concatenation)
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
Can also use elseif
instead of else if
while (condition) {
statements;
}
do {
statements;
} while (condition);
break
and
continue
keywords also behave as in Java (do not use these in this course)
function name(parameterName, ..., parameterName) {
statements;
}
function calculate_profit($cost, $price, $qty) {
return ($price / $cost) * $qty;
}
name(expression, ..., expression);
$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?
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.
$name = array(); # create
$name = array(value0, value1, ..., valueN);
$name[index] # get element value
$name[index] = value; # set element value
$name[] = value; # append 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)
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;
$a = array(); # empty array (length 0)
$age["Whitney"] = 17; # stores 17 at the location where "Whitney" is stored
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 |
$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")
The array in PHP replaces many other data structures in Java
A convenient way to loop over each element of an array without indices
foreach ($array as $variableName) {
...
}
$pups = array ("Mowgli", "Abby", "Archie", "Pascal");
foreach ($pups as $pup) {
echo "Mowgli boops $pup\n"; # even himself
}