Great work on CP3!
Reminder HW3 Milestone 1 is due Monday
GET vs. POST in AJAX requests
Introduction to PHP!
There are two common ways to make AJAX requests to a server.
"?param1=value1¶m2=value2"
(same as what you've been doing)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.
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?
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);
}
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);
}
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.
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 |
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:
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 Local ServersThere 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)
.php
Files with MAMP Local ServerRemember to start MAMP and:
.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!
To stop the server, type Ctrl+Shift+P and type "Php Server: Stop"
.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:
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 = "Ethiopian";
echo $favorite_food[2]; # prints "h"
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).
# 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?)
(Will review for first part of Monday, but included for practice over the weekend
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)
$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
}
function name(parameterName, ..., parameterName) {
statements;
}
function bmi($weight, $height) {
$result = 703 * $weight / $height / $height;
return $result;
}
name(expression, ..., expression);
$w = 163; # pounds
$h = 70; # inches
$my_bmi = bmi($w, $h);
NULL
$name = "Pascal";
$name = NULL;
if (isset($name)) {
echo "This line isn't going to be printed";
}
A variable is NULL
if
NULL
unset
functionCan test if a variable is NULL
using the isset
function
NULL
prints as an empty string (no output)