PHP: GOING DYNAMIC PA 70b – Giordon Stark. Table of Contents Review of Last Time Getting our hands...

55
PHP: GOING DYNAMIC PA 70b – Giordon Stark

Transcript of PHP: GOING DYNAMIC PA 70b – Giordon Stark. Table of Contents Review of Last Time Getting our hands...

PHP: GOING DYNAMIC

PA 70b – Giordon Stark

Table of Contents

Review of Last TimeGetting our hands dirty

Generalized Functions Going global and passing by reference

Forms Superglobals

$_SESSION, $_COOKIE, $_POST, $_GET

Demonstration of PaginationPractice Session: The Groan (ugh) Game

BECAUSE NOT EVERYONE HAS PERFECT MEMORY RECALL.

A Review of Last Time

List Tags - DONE Form Tags – Next Week!

Ordered List Start: <ol></ol> List Item: <li></li>

Unordered List Start: <ul></ul> List Item: <li></li>

Definition List Start: <dl></dl> Term: <dt></dt>

Description: <dd></dd>

<form></form> Input Control: <input />

<button></button> Text Area:

<textarea></textarea> Select List:

<select></select> Option: <option></option> Group: <optgroup></optgroup>

Label: <label></label> Fieldset:

<fieldset></fieldset> Legend: <legend></legend>

HTML Tags

History of PHP

http://www.php.net/manual/en/history.php.php PHP/FI 2.0 PHP: Hypertext Preprocessor

(don’t you love recursion?)

“PHP is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly.”

What is PHP?

Server-Side Language HTML, CSS, JavaScript are all client-side (involves the

browser).It gets processed and parsed before it even

reaches the client

Variables

Stores a valueReused throughout your codeCan be thought of as a programming construct used to

store both numeric and non-numeric dataContents can be altered during program executionCan be compared with each otherSome Types of variables

integers, floating point numbers, strings and arraysWhat makes it different than all other languages?

In many languages, it's essential to specify the variable type before using it: for example, a variable may need to be specified as type integer or type array. Give PHP credit for a little intelligence, though: it automagically determines variable type by the context in which it is being used!

Variables

All variables are defined with the dollar sign ($) $<<variable name>>

Some proper rules PHP variables must start with a letter or underscore "_". PHP variables may only be comprised of alpha-numeric

characters and underscores. a-z, A-Z, 0-9, or _ . Variables with more than one word should be separated

with underscores. $my_variable Variables with more than one word can also be

distinguished with capitalization. $myVariable Variables are case-sensitive

$foo != $Foo != $FOO

Variables

Quotes can lead to many of the common errors in codes

Echo uses quotes to define the beginning and end of the string, so you must use one of the following tactics if your string contains quotations: Don't use quotes inside your string (what if you need

quotes?) Escape your quotes that are within the string with a

backslash. To escape a quote just place a backslash directly before the quotation mark, i.e. \"

Use single quotes (apostrophes) for quotes inside your string

Strings

We have used double-quotes and will continue to use them as the primary method for forming strings.

Double-quotes allow for many special escaped characters to be used that you cannot do with a single-quote string. $newline = "A newline is \n“; $return = "A carriage return is \r“; $tab = "A tab is \t“; $dollar = "A dollar sign is \$“; $doublequote = "A double-quote is \"";

Once again, a backslash is used to escape a character. If you try to escape something that does not need to be

escaped, it will display the backslash as well… Try escaping a backslash!

Arithmetic Operators

Arithmetic Operators http://www.php.net/manual/en/language.operators.arithm

etic.php

Example Name Result

-$a Negation Opposite of $a.

$a + $b Addition Sum of $a and $b.

$a - $b Subtraction Difference of $a and $b.

$a * $b Multiplication Product of $a and $b.

$a / $b Division Quotient of $a and $b.

$a % $b Modulus Remainder of $a divided by $b.

Comparison Operators

Comparisons are used to check the relationship between variables and/or values.

They always return the Boolean variable type $x=4, $y=5

Operator English Example Result

== Equal To $x == $y false

!= Not Equal To $x != $y true

< Less Than $x < $y true

> Greater Than $x > $y false

<= Less Than or Equal To $x <= $y true

>= Greater Than or Equal To

$x >= $y false

Combinations of Operators

Sometimes you want to have a ‘counter’ variable so that you increment by one: $counter = $counter +5;

The better/shortcut way of doing this is: $counter +=5;Operator English Example Equivalent Operation

+= Plus Equals $x += 2; $x = $x + 2;

-= Minus Equals $x -= 4; $x = $x - 4;

*= Multiply Equals $x *= 3; $x = $x * 3;

/= Divide Equals $x /= 2; $x = $x / 2;

%= Modulo Equals $x %= 5; $x = $x % 5;

.=Concatenate Equals

$my_str.="hello";

$my_str = $my_str . "hello";

Includes

Takes a file name and simply inserts that file's contents into the script that issued the include command

Efficient? Common Header for all files, regardless! Instead of having to update the links on several web

pages, you can simply change the header file

Requires

Just like includes, but one major differenceWhen you include a file with the include

command and PHP cannot find it you will see an error message

The rest of the file executed… maybe we don’t want this. If we change the command to require, what happens?

Comparison Operators

Example Name Result

$a == $b Equal TRUE if $a is equal to $b.

$a === $b IdenticalTRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)

$a != $b Not equalTRUE if $a is not equal to $b.

$a <> $b Not equalTRUE if $a is not equal to $b.

$a !== $b Not identical

TRUE if $a is not equal to $b, or they are not of the same type. (introduced in PHP 4)

$a < $b Less thanTRUE if $a is strictly less than $b.

$a > $b Greater thanTRUE if $a is strictly greater than $b.

$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.

$a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.

Logical Operators

The conditional is a statement which we evaluate using comparison operators If you wish to evaluate multiple statements at the

same time, use logical operators http://www.php.net/manual/en/language.operators.logi

cal.php

Example Name Result

$a and $b And TRUE if both $a and $b are TRUE.

$a or $b Or TRUE if either $a or $b is TRUE.

$a xor $b XorTRUE if either $a or $b is TRUE, but not both.

! $a Not TRUE if $a is not TRUE.

$a && $b And TRUE if both $a and $b are TRUE.

$a || $b Or TRUE if either $a or $b is TRUE.

If, Elseif, Else

Take the following codeif(conditional1) {

//do this when conditional1 is true} else if(conditional2) {

//do this when conditional2 is true} else {

//do this when both conditional1 and conditional2 are false

}

Conditional Example

Properties of a triangle: length of 2 sides always greater than third side.

Property of a right triangle: a^2+b^2=c^2 (Pythagorean’s Theorem)

Variables: $a,$b,$c = length of sides of triangle (integer)

if($a+$b < $c || $a+$c < $b || $b+$c < $a){echo “That is not a triangle!”;

} else if($a^2+$b^2==$c^2 || $a^2+$c^2==$b^2 || $b^2+$c^2==$a^2){echo “That is a right triangle!”;

} else {echo “That’s a regular triangle.”;

}

One Last Example (revisited)

The code might look something like thisswitch($state){

case “Florida”:echo “It’ll be a quick 5 hour flight!”;

break;case “California”:

echo “You’re already there silly!”;break;…default:

echo “You’re going out of country? Expect at least a 10 hour flight buddy…”;

break;

A Special Trick…

If the thought of confusing people who read your code makes you feel warm and tingly, you're going to love the ternary operator, represented by a question mark (?). This operator, which lets you make your conditional statements almost unintelligible, provides shortcut syntax for creating a single-statement if-else block.

For Example if ($numTries > 10) {

     $msg = 'Blocking your account...';     } else {     $msg = 'Welcome!'; }

Can be replaced with $msg = $numTries > 10 ? 'Blocking your account...' : 'Welcome!';

While Loops

While loops Depends on a conditional While some condition is true, keep looping.while(condition is true) {

//do something} The following while loop prints out all even numbers

(multiples of two) between two numbers, $upper and $lower:

while($upper >= $lower){if(!$lower%2){echo $lower.’<br />’;}$lower++;

}

For Loops

They are very powerful and allows one to create large outputs of repetitive HTML with very little PHP coding involved. As an example, remember the <sup> tag? Let’s make a loop that nests 100 of them!

$opening = null;$closing = null;for($i=0;$i<100;$i++){

$opening .= ‘<sup>’;$closing .= ‘</sup>’;

}

echo $opening.’I\’m nested!’.$closing;

Functions

A function is… "a block of statements that can be grouped together as a named

entity.“ a set of program statements which perform a specific task, and which

can be "called", or executed, from anywhere in your programWhy are functions good?

user-defined functions allow you to separate your code into easily identifiable subsections - which are easier to understand and debug

functions make your program modular, allowing you to write a piece of code once and then re-use it multiple times within the same program

functions simplify code updates or changes, because the change needs only to be implemented in a single place (the function definition)

Functions thus save time, money and electrons... and I know the electrons at least will thank you!

Functions

Here’s a typical structure of a functionfunction function_name (optional arguments) {

    statement 1...     statement 2...     .     .     .     statement n...

}

ACTUALLY, NOT REALLY… IT ’S TIME TO LEARN SOME MORE PHP!

It’s Peanut Butter Jelly Time!

Functions

Continuing our discussion on functions, we’ll wrap it up by talking about globality/locality of variables.

Variables outside of a function and variables inside the function are generally completely different.

Usually, the variables used within a function are "local" - meaning that the values assigned to them, and the changes made to them, are restricted to the function space alone. http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture

6/example/exercise1.php

Functions

In other words, the variable inside the function is insulated from the identically-named variable in the main program.

Variables inside a function are called "local" variables because they only exist within the function in which they are defined.

The reverse is also true: variables defined inside a function cannot be "seen" outside it. http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture

6/example/exercise2.php

Functions – Going Global

To make a variable global, simply put the global keyword in front of it. http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture6/e

xample/exercise3.phpOnce a variable is declared global, it is

available at the global level, and can be manipulated both inside and outside a function.

PHP also has superglobals http://www.php.net/manual/en/reserved.variables.php http://www.php.net/manual/en/language.variables.scope.

phpWe’ll work with $_COOKIE, $_SESSION,

$_POST, $_GET today.

Function References

“Passing by reference” versus “Passing by value”All the examples you've seen have involved passing

arguments to a function "by value" - meaning that a copy of the variable was passed to the function, while the original variable remained untouched

PHP also allows you to pass "by reference" - meaning that instead of passing a value to a function, you pass a reference to the original variable, and have the function act on that instead of a copy – a way to go global without making the variable global! http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture6/example/exerci

se4.phpNotice the ampersand (&) before the argument in the

function definition - tells PHP to use the variable reference instead of the variable value

GOOD FORM, FORMAL WEAR, DEFENSIVE FORMATION… NOW!

Forms!

Client Side Code

<form></form>Input Control: <input />Text Area: <textarea></textarea>Select List: <select></select>

Option: <option></option> Group: <optgroup></optgroup>

Label: <label></label>Fieldset: <fieldset></fieldset>

Legend: <legend></legend>

Client Side Code

Let’s look at the form tag: <form name=“someForm” method=“{GET/POST}”

action=“{URL}”></form>We have two attributes: method and action.Method defines the method of which the form

is submitted (via the string in URL [GET] or via the HTTP request [POST])

Action defines the URL of which the form is submitted (if left blank, defaults to current page form is found on)

Client Side Code

When you select method=“get”, the values of the form get sent via the url by appending to the end of it. http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture

6/example/exercise5.php Example is also on class website for future reference

When you select method=“post”, the values of the form get sent via HTTP headers (you can’t physically see it, but you can analyze your HTTP headers)

Client Side Code

If you analyze the form elements, you’ll see the following: Inputs submit their values using the name attribute as the

variable name Textboxes, Radios, Textarea, a drop down select menu all take

one input Checkboxes can take in multiple values, so we store all

possible values using an array for the element name; “hobbies[]” in our example

Labels have a “for” attribute which links the text to a form element with the given id. By assigning a label, the ‘clickable’ area of a form element is increased

Server Side Code

To get any of the values obtained via the URL (get method), use the $_GET superglobal. In the previous example, we can dump this variable after the form is submitted to see the output.

To get any of the values obtained via HTTP headers (post method), use the $_POST superglobal. http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture6/example/

exercise6.phpWe note that $_GET and $_POST are arrays.

Intuitively, we do not know how to deal with them yet, but for right now, simply use the following notation to obtain the value stored in “variable_name”: $_GET[“variable_name”]

I NEVER LACK MATERIAL FOR MY HUMOR COLUMN WHEN CONGRESS IS IN SESSION.

Sessions

Why do we need them?

"HTTP is a stateless protocol, and the Internet is a stateless development environment".

HTTP, the HyperText Transfer Protocol that is the backbone of the Web, is unable to retain a memory of the identity of each client that connects to a Web site, and therefore treats each request for a Web page as a unique and independent connection, with no relationship whatsoever to the connections that preceded it

This "stateless environment" works great so long as you're aimlessly surfing the Web, but it can cause a serious headache for sites that actually depend on the data accumulated in previous requests The most common example is that of an online shopping cart - in a stateless

environment, it becomes difficult to keep track of all the items you've shortlisted for purchase as you jump from one catalog page to another.

Why do we need them?

Obviously, then, what is required is a method that makes it possible to "maintain state", allowing client connections to be tracked and connection-specific data to be maintained. And thus came about cookies, which allow Web sites to store client-specific information on the client system, and access the information whenever required.

A cookie is simply a file, containing a series of variable-value pairs and linked to a domain. When a client requests a particular domain, the values in the cookie file are read and imported into the server environment, where a developer can read, modify and use them for different purposes.

A cookie is a convenient way to carry forward data from one client visit to the next.

Why do we need them?

Another common approach is to use a session to store connection-specific data; this session data is preserved on the server for the duration of the visit, and is destroyed on its conclusion.

Sessions work by associating every session with a session ID (a unique identifier for the session) that is automatically generated by PHP.

This session ID is stored in two places: on the client using a temporary cookie, and on the server in a flat file or a database.

By using the session ID to put a name to every request received, a developer can identify which client initiated which request, and track and maintain client-specific information in session variables (variable-value pairs which remain alive for the duration of the session and which can store textual or numeric information).

In summary

Sessions and cookies thus provide an elegant way to bypass the stateless nature of the HTTP protocol, and are used on many of today's largest sites to track and maintain information for personal and commercial transactions.

Typically, you use a session to store values that are required over the course of a single visit, and a cookie to store more persistent data that is used over multiple visits.

Sessions

http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture6/example/exercise7.php

Each time you visit this page, the counter increases via a session.

If you go to another website, and then come back to the page, the session still exists. A session persists as long as the browser hasn’t closed. It is like a cookie that gets erased when the browser is closed.

Start it with session_start() which checks to see whether a session already exists, and either restores it (if it does) or creates a new one (if it doesn't).

Sessions

Session variables are registered by adding a new key to the $_SESSION superglobal array and can be accessed anytime during the session. In the example above, a key named counter has been

added to the $_SESSION array. The first time a session is created, this key will have the value 0. On every subsequent request for the page during the same session, the previous value of the counter will be retrieved and incremented by 1.

All sessions are saved (by default) to the /tmp directory of your PHP distribution.

Sessions

As an example of how sessions can really be powerful for login systems, check this out. http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture

6/example/exercise8.phpThe idea here is that for the same page, we

can create ‘sub-pages’ which the user sees depending on his state of being logged-in or not.

Sessions

Word to the wise: It's important to note that the call to session_start() must appear first, before any output is generated by the script. This is because the PHP session handler internally uses in-memory

cookies to store session data, and the cookie creation headers must be transmitted to the client browser before any output.

If you get an error like the following: http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture6/example/exerci

se9.php It's usually because somewhere, somehow, some output has found

its way to the browser before session_start() was called. Even a carriage return or a blank space outside the PHP tags surrounding session_start() can cause this error, so watch out for them.

For more information on sessions, refer to this page http://www.php.net/manual/en/ref.session.php

C IS FOR COOKIE AND COOKIE IS FOR C

Cookies

Cookies

As we mentioned, sessions are like temporary cookies. A session works by using an in-memory cookie, which

explains why it's only active while the browser instance that created it is active; once the browser instance is terminated, the memory allocated to that instance is flushed and returned to the system, destroying the session cookie in the process

It's important to remember that, since cookies are stored on the user's hard drive, you as the developer have very little control over them.

The Rules

Before you start using cookies, there are a few things you should be aware of:

Since cookies are used to record information about your activities on a particular domain, they can only be read by the domain that created them

A single domain cannot set more than twenty cookies, and each cookie is limited to a maximum size of 4 KB

A cookie usually possesses six attributes, of which only the first is mandatory. Here they are: name: the name of the cookie value: the value of the cookie expires: the date and time at which the cookie expires path: the top-level directory on the domain from which cookie data can be

accessed domain: the domain for which the cookie is valid secure: a Boolean flag indicating whether the cookie should be transmitted only

over a secure HTTP connection

Cookies

To make magic, we set cookies using the setcookie() function (unlike sessions, we simply need to create the new variable).

Once we set a cookie, we can do whatever we would like with it. http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture6/example/exer

cise10.phpNote that this works even if you terminate the browser

instance, restart it and visit the page again, completely different than what we saw with sessions.

To terminate a cookie, you simply need to set the expire time to a current time that already passed.

Note that similarly with session_start(), setcookie() needs to be called before any output is sent to the browser.

Using Sessions and Cookies for Authentication

As a thought experiment, try the following.Assume we have a database that stores

username/password value pairs which we use to authenticate users. When a user types in their username and password, we encrypt and compare to our database records. If it matches, we can set a session variable that says “They’ve logged in”. From there on, any page that requires restricted access simply needs to check the value of this session variable (as well as if it exists).

I ’LL SHOW YOU GUYS HOW TO CREATE A SIMPLE PAGINATION SYSTEM.

In-Class Exercise

Why might this be related to forms?

The whole essence of forms is that we take in user input. Form tags are there as a natural method for doing so. Other methods often include manipulating the URL to pass certain values to change the way the data appears on the page. In this example I’ll show you, I’ll develop a system that paginates a bunch of information in an array. This array can be formed by reading a text file, reading a database. For our purposes, we don’t need to know about arrays, but every other portion of the script is important.

PRACTICE MAKES PERFECT, BUT NOBODY’S PERFECT… WHY PRACTICE?

Practice Session

The Groan Game

As it turns out, I originally got the idea from Brian Merlob for this game and I thought it would be a perfect fit for this lecture.

The Background: You and another player (the computer) have a set of 2 die. You

take turns rolling the die trying to get 100 points (based on the numbers you roll).

The rules: On your turn, you can choose to roll or stop (you must roll at least

once on your turn). If one dice is a ‘1’, your turn ends and you get no points for that turn. If both die are ‘1’s (snake eyes), you lose all points you have accumulated and your turn ends. Each time you roll, you add up your rolls and that’s your temporary value for the turn. When you end your turn, you add this temporary value to your total.

The Logistics of The Groan Game

If you imagine, you’ll need to be able to: (Sessions) Remember their total value and temporary turn value (Form Inputs) Use their input on what action the player chooses to

take which is either to roll or to end their turn (Random) Generate a random die – lookup the “rand()” function on

www.php.net You’ll want to program a computer player.

Based on probability, there are 36 different outcomes with 2 die. Out of these 36, 11 of them result in at least one ‘1’ showing up. Thus, 25/36 is the probability of not getting a ‘1’. The expected number of turns is 1/(25/36) = 1.44. We expect 7 points per roll (the average value of a roll is 3.5, so two die is 7). 7*1.44 = 10.08 points per roll.

Conclusion: program the computer to end his turn when he has accumulated at least 10 points on a single turn (optimal strategy).