+ All Categories
Home > Documents > Lecture 9 Introduction to PHP

Lecture 9 Introduction to PHP

Date post: 30-Dec-2015
Category:
Upload: cornelia-corbin
View: 39 times
Download: 1 times
Share this document with a friend
Description:
Lecture 9 Introduction to PHP. Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU. Server-side Web-scripting is mostly about connecting web-sites to back-end servers such as databases. This enables two way communication: - PowerPoint PPT Presentation
Popular Tags:
55
Lecture 9 Introduction to PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU
Transcript
Page 1: Lecture 9 Introduction to PHP

Lecture 9Introduction to PHP

Presented ByDr. Shazzad Hosain

Asst. Prof. EECS, NSU

Page 2: Lecture 9 Introduction to PHP

2

Server-side Scripting

• Server-side Web-scripting is mostly about connecting web-sites to back-end servers such as databases.

• This enables two way communication:– Server to client: Web-pages can be

assembled from back-end server output;– Client to Server: Customer-entered

information can be acted upon.

See next page for data flow in server-side scripting.

Page 3: Lecture 9 Introduction to PHP

3

Server-side Scripting (cont’d)

Page 4: Lecture 9 Introduction to PHP

4

What do You Need?• Where to Start?

– Install an Apache server on a Windows or Linux machine. Or IIS on wndows.

– Install PHP on a Windows or Linux machine – Install MySQL on a Windows or Linux machine– Or, Install XAMPP/WAMP to get all-in-one solution

• PHP + MySQL– PHP combined with MySQL are Cross-platform

(means that you can develop in Windows and serve on a Unix platform), Open source, Compatible with leading web servers, Faster and Truly Portable.

Page 5: Lecture 9 Introduction to PHP

Introduction to PHP

Page 6: Lecture 9 Introduction to PHP

6

PHP Tag Styles – The good…• XML Style:

<?php print “this is XML style”;

?>• Short Style:

<?print “this is ASP style”;

?>

• To use Short style the PHP you are using must have “short tags” enabled in its config file… this is almost always the case.

Page 7: Lecture 9 Introduction to PHP

7

Comments• Why do we go on about comments so much?• because without them, marking would hurt our heads.

<? //C style comment

#perl style comment

/* C++ multi line comment */

?>

Page 8: Lecture 9 Introduction to PHP

8

PHP is for Lazy People• You know that means you! Don’t need to work with types and

conversions.

• Basic data types– numbers (integers and real) – strings (Double-quoted "abc“ and single-quoted 'abc')– booleans (true,false )

• Dynamic typing– Don't have to declare types – Automatic conversion done

• all variables in PHP are denoted with a leading dollar sign ($);– variables have default values.

Page 9: Lecture 9 Introduction to PHP

9

Variables in action<?

$x = false;         // boolean type $x = true;

$x = 10;         // decimal $x = 1.45;         // Floating point $x = 0x1A;         // hexadecimal 

$x = "mmm\"oo'oo\n";     // mmm"oo'oo  and a new line $x = 'mmm"oo\'oo\n';     // string = mmm"oo'oo\n

$y = &$x         // Reference

$x[1] = 10         // array of decimals $x["name"] = “jimbo";    // associative array $x[2]["lala"] = "xx";    // a two dimensional array

?>

Page 10: Lecture 9 Introduction to PHP

10

Variables (cont’d)Assigning variables:

$pi = 3 + 0.14159 // approximately

Re-assigning variables:

$my_num_var = “it is not a number”;$my_num_var = 5;

Unassigned variables:• PHP ensures that variables have default values

(they can be printed unassigned).

Page 11: Lecture 9 Introduction to PHP

11

Variables (cont’d)• Checking assignment with IsSet:

$set_var = 0; //set_var has a value //never_set does not

if (IsSet($set_var)) print(“set_var has a value. <BR>”);

if (IsSet($never_set)) print(“never_set has a value. <BR>”);else print(“never_set has no value. <BR>”);

• If you use an unset variable, system will complain.

Page 12: Lecture 9 Introduction to PHP

12

Switching Modes

<? if(strstr($HTTP_USER_AGENT,"MSIE")) {

?><b>You are using Internet Explorer</b>

<? } else {

?><b>You are not using Internet Explorer</b>

<? }

?>

Here we have flicked back

to HTML again

Here we are in PHP-mode

Using the arrow-

question mark tag we can quickly

switch modes

Page 13: Lecture 9 Introduction to PHP

13

Variable Scope

• The 3 basic types of scope in PHP is:

– Global variables declared in a script are visible throughout that script, but not inside functions

– Variables used inside functions are local to the function

– Variables used inside functions that are declared as global refer to the global variable of the same name

Page 14: Lecture 9 Introduction to PHP

14

Operators• Arithmetic Operators: +, -, *, / , %, ++, --• Assignment Operators: =, +=, -=, *=, /=, %=

• Comparison Operators: ==, !=, >, <, >=, <= • Logical Operators: &&, ||, !• String Operators: . , .=

Example Is the same asx+=y x=x+yx-=y x=x-yx*=y x=x*yx/=y x=x/yx%=y x=x%y

$a = "Hello ";$b = $a . "World!"; //now $b contains "Hello World!"

$a = "Hello ";$a .= "World!";

Page 15: Lecture 9 Introduction to PHP

15

Output- echo

For printing to output we can use:• echo - to print a string as argument.

echo “This prints in the browser.”; or echo(“This prints in the browser.”); or echo “This prints”, “in the browser.”;

• Note that echo will also work with the string concatenation operator . as:

echo “This prints” . “in the browser.”; orecho(“This prints” . “in the” . “browser.”); but echo(“This causes a”, “PARSE ERROR!”);

Page 16: Lecture 9 Introduction to PHP

16

Output- print (cont’d)• print - is very similar to echo, with two important differences:

– can accept only one argument;– returns a value, which represents whether the print

statement succeeded;• returned value 1 means that printing was successful;• returned value 0 means that printing was unsuccessful.

– Example: print(“3.14159”); //print a string

print(3.14159); //print a number

– numbers are converted to strings before they are printed.

Page 17: Lecture 9 Introduction to PHP

17

Output (cont’d)

• variables and strings $animal = “Antelope”; $heads = 1; $legs = 4; print(“$animal has $heads head(s). <BR>”); print(“$animal has $legs leg(s). <BR>”);

Output Antelope has 1 head(s). Antelope has 4 leg(s).

• Use single quotes to print directories print(‘C:\newcode\myphp.php’);

Page 18: Lecture 9 Introduction to PHP

18

Output (cont’d)

• HTML and line breaks– C programmers be aware that the new line

character “\n” is not the same as “<BR>”;– \n prints a new line in the HTML code generated,

while <BR> prints a new line on the browser;– what is the HTML and browser output of the

statement: print(“Is this only \n\n one line? <BR>”);

(left as an exercise).

Page 19: Lecture 9 Introduction to PHP

19

Simple String functionschr - Return a specific character ord - Return ASCII value of charactersprintf - Return a formatted stringstrlen - Get string lengthstrpos - Find position of first occurrence of a

stringstrrev - Reverse a stringstrtolower - Make a string lowercasestrtoupper - Make a string uppercasestr_replace - Replace all occurrences of the search

string with the replacement string

Page 20: Lecture 9 Introduction to PHP

20

PHP Control Statements

• Just for the record what’s the same as C++/Java?

– For Loops– While Loops– If Statements– Break, Continue, Exit, Switch, etc.

• The main concepts which differ in syntax are:– Functions– Classes

Page 21: Lecture 9 Introduction to PHP

21

If – exists• You often need to check whether a variable

exists in PHP.

• There are two ways to do this…

if ($a){

print “\$a exists";

}else{

print “\$a exists"; }

if (!empty($a)){

print “\$a exists";}else{ print “\$a exists"; }

Page 22: Lecture 9 Introduction to PHP

22

Conditionals: if else<html><head></head><body>

<?php$d=date("D");if ($d =="Fri") echo "Have a nice weekend! <br/>"; else echo "Have a nice day! <br/>";

$x=10;if ($x==10){ echo "Hello<br />"; echo "Good morning<br />";}?></body></html>

if (condition)code to be executed if condition is true;elsecode to be executed if condition is false;

date() is a built-in function that can be called with many different parameters to return the date (and/or local time) in various formats

In this case we get a three letter string for the day of the week.

Page 23: Lecture 9 Introduction to PHP

<html><head></head><body> <!–- switch-cond.php --><?php$x = rand(1,5); // random integerecho “x = $x <br/><br/>”;switch ($x){case 1: echo "Number 1"; break;case 2: echo "Number 2"; break;case 3: echo "Number 3"; break;default: echo "No number between 1 and 3";}?></body></html> 23

Conditionals: switch

switch (expression){case label1: code to be executed if expression = label1; break; case label2: code to be executed if expression = label2; break;default: code to be executed if expression is different from both label1 and label2;}

Page 24: Lecture 9 Introduction to PHP

24

Looping: while and do-whileCan loop depending on a condition

<html><head></head><body>

<?php $i=1;while($i <= 5){ echo "The number is $i <br />"; $i++;}?>

</body></html>

loops through a block of code if and as long as a specified condition is true

<html><head></head><body>

<?php $i=0;do{ $i++; echo "The number is $i <br />";}while($i <= 10);?>

</body></html>

loops through a block of code once, and then repeats the loop as long as a special condition is true

Page 25: Lecture 9 Introduction to PHP

25

Looping: for and foreachCan loop depending on a "counter"

<?phpfor ($i=1; $i<=5; $i++){ echo "Hello World!<br />";}?>

loops through a block of code a specified number of times

<?php$a_array = array(1, 2, 3, 4);foreach ($a_array as $value) { $value = $value * 2; echo “$value <br/> \n”;}?>

loops through a block of code for each element in an array

<?php $a_array=array("a","b","c");foreach($a_array as $key=>$value){ echo $key." = ".$value."\n";}?>

Page 26: Lecture 9 Introduction to PHP

26

PHP Functions• Functions in PHP are not case sensitive.• Be careful of this because variable naming is case sensitive

function my_function(){print “My function was called”;

}

• Functions can be created anywhere in your PHP code• However good style demands they should always be at the

top of your code

Page 27: Lecture 9 Introduction to PHP

27

Do what is neatest…<?

Function my_function(){

print “My function was called”;}

?>

<?Function my_function(){

?>My function was

called<?

}?>

IS IDENTICAL TO…

Page 28: Lecture 9 Introduction to PHP

28

Passing Parameters• As normal you don’t have to specify the types of your

parameters...• Be careful of this because variable naming is case

sensitive

function display_table($data){print “<TABLE>”;

for ($i=0; $i<sizeof($data); $i++) print “<TR><TD> $data[$i]

</TD></TR>”;

print “</TABLE>”;}

Page 29: Lecture 9 Introduction to PHP

29

Defaults & Passing by Reference• As with other languages you can set defaults. PHP requires that

you do specify the correct number of parameters in a call.

• Equally you don’t have to pass by value – an ampersand will mean the variable is passed by reference and so any changes to it are global:

function increment(&$value, $amount=1){$value = $value + $amount;

}

Page 30: Lecture 9 Introduction to PHP

30

Example…function larger($x, $y){if ($x > $y)

return $x;

if ($x < $y) return $y;

if ($x == $y) return “x and y have the same value”;

}

Page 31: Lecture 9 Introduction to PHP

31

Variable ScopeThe scope of a variable is the

context within which it is defined.

<?php$a = 1; /* global scope */ function Test(){ echo $a; /* reference to local scope variable */ } Test();?>

The scope is local within functions.

<?php$a = 1;$b = 2;function Sum(){ global $a, $b; $b = $a + $b;} Sum();echo $b;?>

global

refers to its global version.

<?phpfunction Test(){ static $a = 0; echo $a; $a++;}Test(); Test();Test(); ?>

static

does not lose its value.

Page 32: Lecture 9 Introduction to PHP

32

Arrays in PHP• Arrays in PHP are associative, i.e. values of elements are stored

in association with the key values, rather than a strict linear order.

/* Direct assignment: create array $state_loc, and assign location with key = ‘San Mateo’ equal to ‘California’ */

$state_loc[‘San Mateo’]= ‘California’;

//…later assign ‘California’ to $state

$state = state_loc[‘San Mateo’];

Page 33: Lecture 9 Introduction to PHP

33

Arrays (cont’d)

• The array() construct

$fruit_basket = array(‘apple’,‘banana’);

• which can also be written as:

$fruit_basket[1] = ‘apple’;$fruit_basket[2] = ‘banana’;

• or (almost) equivalent to:

$fruit_basket[] = ‘apple’; //here indices start$fruit_basket[] = ‘banana’; //from 0 (not 1).

Page 34: Lecture 9 Introduction to PHP

34

Arrays (cont’d)

• Specifying indices using array()

$fruit_basket = array(0 =>‘apple’, 1 =>‘banana’ );

• We could also write:

$fruit_basket = array(‘red’ =>‘apple’, ‘yellow’ =>‘banana’ );

Page 35: Lecture 9 Introduction to PHP

35

Arrays (cont’d)

• Multi-dimensional arrays as arrays with elements that are arrays themselves.

$basket[0][0] = ‘apple’; $basket[0][1] = ‘banana’; $basket[1][0] = ‘rose’; $basket[1][1] = ‘tulip’;

Page 36: Lecture 9 Introduction to PHP

36

Arrays (cont’d)• Alternatively:

$basket = array(0 => array(0 => ‘apple’, 1 => ‘banana’ ), 1 => array(0 => ‘rose’, 1 => ‘tulip’) ) );

Page 37: Lecture 9 Introduction to PHP

37

Arrays (cont’d)• Or, for a more meaningful version:

$basket = array(‘fruits’ => array(‘red’ => ‘apple’, ‘yellow’ => ‘banana’ ), ‘flowers’ => array(‘red’ => ‘rose’, ‘violet’ => ‘tulip’) ) );

Page 38: Lecture 9 Introduction to PHP

38

Arrays (cont’d)• The program:

$kind = ‘flower’;$colour = ‘red’;print(“You want a {$basket[$kind][$colour]}.”);

• Outputs:

You want a rose.

Page 39: Lecture 9 Introduction to PHP

39

The list() construct• the list() construct is the inverse of array(), since array()

packages its arguments into an array, and list() takes the array apart again into individual variable assignments.

$fruits = array(‘apple’, ‘banana’, ‘orange’);list($red, $yellow) = $fruits;print(“The $red is red and the $yellow isyellow.<BR>”);

• Output:

The apple is red and the banana is yellow.

Page 40: Lecture 9 Introduction to PHP

40

Merging Arrays• array_merge()

$fruits = array("apples", "oranges", "pears");

$vegetables = array("potatoes", “onions", "carrots");

$newarray = array_merge($fruits, $vegetables);

$howmany = count($newarray);

print "$howmany"; // will output 6 to the screen

Page 41: Lecture 9 Introduction to PHP

41

Accessing Array Elements

<?php

$vegetables = array("potatoes", “onions", "carrots");

for ($i=0; $i< count($vegetables); $i++){ print "$vegetables[$i]<br>\n"; }

?>

Page 42: Lecture 9 Introduction to PHP

42

each() function

$vegetables = array("potatoes", “onions", "carrots");

for ($i=0; $i< count($vegetables); $i++){ $Line = each($vegetables); print "$Line[key] is $Line[value]<br>\n"; }

Page 43: Lecture 9 Introduction to PHP

43

Array Functions (the boring ones)

count - Count elements in a variable sizeof - Get the number of elements in variable

array_pop - Pop the element off the end of array array_push - Push one or more elements onto the end of arrayarray_shift - Shift an element off the beginning of array

array_search - Searches the array for a given value and returns the corresponding key if successful

sort - Sort an array into numerical order

Page 44: Lecture 9 Introduction to PHP

44

…er.. The exciting ones?

array_reverse - Return an array with elements in reverse orderarray_flip - Flip all the values of an array keys become valuesarray_unique - Removes duplicate values from an array

array_values - Return all the values of an arrayarray_sum - Calculate the sum of values in an array.

extract – converts arrays to scalar variablesarray_rand - Pick 1 or more random entries from the arrayshuffle – randomly reorders the elements in an array

Page 45: Lecture 9 Introduction to PHP

45

Constants• A constant is an identifier (name) for a simple value. A constant is case-sensitive by default. • By convention, constant identifiers are always uppercase.

<?php // Valid constant names define("FOO", "something"); define(“MAX", 100); define(“PI", 3.14159); // Invalid constant names define("2FOO", "something");

You can access constants anywhere in your script without regard to scope.

Page 46: Lecture 9 Introduction to PHP

46

Exploding Strings

• Not a new firework but rather a way of breaking a string down and putting it into an array.

• And its useful, especially if you are doing anything with cookies.

$email = “[email protected]”;$email_array = explode(“@”, $email);$domains = explode(“.”, $email_array[0]);

• Implode() reverses the process.$domain[0] = “cs”

$domain[1] = “nsu”

$domain[2] = “edu”

Page 47: Lecture 9 Introduction to PHP

47

Changing Case• Most people who use your sites will be muppets. (although your sites for

HLL will probably only be viewed by members of staff so draw your own conclusions).

• Whatever you tell them to do, they won’t enter data in the format you want and this will matter. Login names are classic examples of this.

• Imagine someone types “aStOn VillA” into a field…

Strtoupper()

Strtolower()

Ucfirst()

Ucwords()

Turns string to uppercase

Turns string to lowercase

Capitalises first character

Capitalises every word

ASTON VILLA

aston villa

Aston villa

Aston Villa

Page 48: Lecture 9 Introduction to PHP

48

Problem Characters• Some characters cause you no end of problems.

– Specifically ‘ and “.

• For example if you have a field asking for a name and someone sends you back: Ronnie O’Sullivan, consider the following code:

Print ‘Welcome to the site $name’;

Print ‘Welcome to the site Ronnie O’Sullivan’;

We need a way of marking, or escaping these characters so that databases such as mysql can understand we meant a literal character.

Page 49: Lecture 9 Introduction to PHP

49

Adding Slashes• To do this escaping normally you just add a \ (backslash). This can be very

painful to do manually.

AddSlashes() a function to do it for you.StripSlashes() reverses the process.

• So if a user typed in:You said to me that “you don’t give guarantees”

• $userInput = AddSlashes($userInput)

You said to me that \“you don\’t give guarantees\”.

Page 50: Lecture 9 Introduction to PHP

50

Crypt• crypt() will encrypt a string that you give it.

• This is especially useful for encrypting items such as passwords.

• This then cannot be reversed – but you can encrypt another string that is entered and then compare it with the stored encrypted string.

• You should always encrypt your users access information if its privacy is essential.

Page 51: Lecture 9 Introduction to PHP

51

Time inside PHP• Time() -- gives you the current UNIX/Windows timestamp

• Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

• You find yourself using this all the time once you have a complicated site. Common examples are:

– Keeping track of login times– Time how long processes are taking

Page 52: Lecture 9 Introduction to PHP

52

Date()

• Time is very useful but not very pretty – who wants to know the number of seconds since the unix epoch !?

• Date() outputs the current time into whatever format you specify:

Print date(“jS F Y”); 25th April 2007Print date("F j, Y, g:i a"); April 25, 2007, 9:46 pmPrint date("H:i:s"); 09:46:17Print date("D M j G:i:s T") ; Fri Apr 25 9:46:17 GMT

Page 53: Lecture 9 Introduction to PHP

53

Formatting the DateA – morning or afternoonj – day of the monthD – day of the week as a three letter word (eg. Mon)F – month of the year as a full stringm – month of the year as a two digit numberG – hour of the dayI – minutes past the hourS – seconds past the minuteT – timezone you are in (eg. GMT)Y – year in 4-digit formatz – day of the year as a number (0-365)

• You can also add a UNIX timestamp as a second argument in the date() function – the formatted string will represent that time.

Page 54: Lecture 9 Introduction to PHP

54

Getting Time and Date

date() and time () formats a time or a date.<?php//Prints something like: Mondayecho date("l");

//Like: Monday 15th of January 2003 05:51:38 AMecho date("l dS of F Y h:i:s A");

//Like: Monday the 15th

echo date("l \t\h\e jS");?>

date() returns a string formatted according to the specified format.

*Here is more on date/time formats: http://uk.php.net/manual/en/function.date.php

<?php$nextWeek = time() + (7 * 24 * 60 * 60); // 7 days; 24 hours; 60 mins; 60secsecho 'Now: '. date('Y-m-d') ."\n";echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";?>

time() returns current Unix timestamp

Page 55: Lecture 9 Introduction to PHP

Recommended