CSE 154

Lecture 13: Intro to PHP

Review: Course outline

HTML: Webpage content

CSS: Webpage presentation

JavaScript: Webpage functionality (client-side)

AJAX: Fetching data from the internet


PHP: Server-side code with PHP

Regular Expressions: Validating input

SQL: Storing data

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

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

PHP

0-based indexing using [] bracket notation

String concatenation is . (period) not +

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

Can be specified with "" or ''

String Functions

            
            # index  0123456789012345
            $name = "Kyle Thayer";
            $length = strlen($name);                # 10
            $cmp = strcmp($name, "Whitaker Brand"); # < 0
            $index = strpos($name, "y");            # 1
            $last = substr($name, 5, 6);           # "Thayer"
            $name = strtoupper($name);              # "KYLE THAYER"
            

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

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
$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) 
  • to append, use bracket notation without specifying an index
  • element type is not specified; can mix types

Functions

function name(parameterName, ..., parameterName) {
	statements;
}		
function bmi($weight, $height) {
	$result = 703 * $weight / $height / $height;
	return $result;
}		
  • parameter types and return types are not written
  • a function with no return statements is implicitly "void"

Calling Functions

name(expression, ..., expression); 

$w = 163; # pounds
$h = 70; # inches
$my_bmi = bmi($w, $h); 
		
  • if the wrong number of parameters are passed, it's an error