php scripting language

61
PHP Scripting language

Upload: ena

Post on 22-Jan-2016

53 views

Category:

Documents


0 download

DESCRIPTION

PHP Scripting language. Something about PHP. PHP = PHP Hypertext Preprocessor Open-source Easy to use ( C-like and Perl-like syntax) Multiplatform Many databases support Many common built-in libraries Pre-installed in Linux distributions. Client Browser. 4. 1. PHP module. 3. Apache. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: PHP Scripting language

PHP Scripting language

Page 2: PHP Scripting language

Something about PHP● PHP = PHP Hypertext Preprocessor ● Open-source

● Easy to use ( C-like and Perl-like syntax) Multiplatform

● Many databases support

● Many common built-in libraries

● Pre-installed in Linux distributions

Page 3: PHP Scripting language
Page 4: PHP Scripting language

How PHP generates HTML/JS Web pages

1: Client from browser send HTTP request (with POST/GET variables)2: Apache recognizes that a PHP script is requested and sends the request to PHP module3: PHP interpreter executes PHP script, collects script output and sends it back4: Apache replies to client using the PHP script output as HTML output

2

Client Browser

1 PHP module3

4

Apache

Page 5: PHP Scripting language

HTML Embedding● SGML style:

<? code ?>● XML style:

<?php code ?>● ASP style:

<% code %>● Javascript style:

<script language=“php”>code</script>

Page 6: PHP Scripting language

Integrated with HTML code

● Possible within a block of statements:

Page 7: PHP Scripting language

Hello World! (web oriented)

<html><head> <title>My personal Hello World! PHP script</title></head><body><?echo “Hello World!”;

?></html>

PHP tag, allow to insert PHP code. Interpretation by PHP module will substitute the code with code output

Page 8: PHP Scripting language

Data types● PHP Manual about data typeshttp://tw2.php.net/manual/en/language.variables.php

● Basic data types– numbers (integers and real) Decimal 1234, Octal

0777, Hex 0xff – strings Double-quoted "abc", single-quoted 'abc' – booleans true,false

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

Page 9: PHP Scripting language

Variables (I)• To use or assign variable $ must be present before the name

of the variable

• The assign operator is '='

• There is no need to declare the type of the variable

• the current stored value produces an implicit type-casting of the variable.

• A variable can be used before to be assigned

$A = 1;

$B = “2”;

$C = ($A + $B); // Integer sum

$D = $A . $B; // String concatenation

echo $C; // prints 3

echo $D;// prints 12

Page 10: PHP Scripting language

Variables (II)• Function isset tests if a variable is assigned or not

$A = 1;

if (isset($A))

print “A isset”

if (!isset($B))

print “B is NOT set”;

• Using $$

$help = “hiddenVar”;

$$help = “hidden Value”;

echo $$help; // prints hidden Value

$$help = 10;

$help = $$help * $$help;

echo $help; // print 100

Page 11: PHP Scripting language

Strings (I)• A string is a sequence of chars

$stringTest = “this is a sequence of chars”;

echo $stringTest[0]; output: t

echo $stringTest; output: this is a sequence of chars

• A single quoted strings is displayed “as-is”

$age = 37;

$stringTest = 'I am $age years old'; // output: I am $age years old

$stringTest = “I am $age years old”; // output: I am 37 years old

• Concatenation

$conc = ”is “.”a “.”composed “.”string”;

echo $conc; // output: is a composed string

$newConc = 'Also $conc '.$conc;

echo $newConc; // output: Also $conc is a composed string

Page 12: PHP Scripting language

Strings (II)

• Explode function

$sequence = “A,B,C,D,E,F,G”;

$elements = explode (“,”,$sequence);

// Now elements is an array with all substrings between “,” char

echo $elemets[0]; // output: A;

echo $elemets[1]; // output: B;

echo $elemets[2]; // output: C;

echo $elemets[3]; // output: D;

echo $elemets[4]; // output: E;

echo $elemets[5]; // output: F;

echo $elemets[6]; // output: G;

Page 13: PHP Scripting language

Arrays (I)• Groups a set of variables, every element stored into an

array as an associated key (index to retrieve the element)$books = array( 0=>”php manual”,1=>”perl manual”,2=>”C manual”);

$books = array( 0=>”php manual”,”perl manual”,”C manual”);

$books = array (“php manual”,”perl manual”,”C manual”);

echo $books[2]; output: C manual

• Arrays with PHP are associative$books = array( “php manual”=>1,”perl manual”=>1,”C manual”=>1); // HASH

echo $books[“perl manual”]; output: 1

$books[“lisp manual”] = 1; // Add a new element

Page 14: PHP Scripting language

• Working on an arrays

$books = array( ”php manual”,”perl manual”,”C manual”);

• Common loop

for ($i=0; $i < count($books); $i++)

print ($i+1).”-st book of my library: $books[$i]”;

• each

$books = array( “php manual”=>1,”perl manual”=>2,”C manual”=>3);

while ($item = each( $books )) // Retrieve items one by one

print $item[“value”].”-st book of my library: ”.$item[“key”];

// each retrieve an array of two elements with key and value of current element

• each and list

while ( list($value,$key) = each( $books ))

print “$value-st book of my library: $key”;

// list collect the two element retrieved by each and store them in two different // variables

Arrays (II)

Page 15: PHP Scripting language

Arrays (III)• Multidimensional arrays

$books = array( array(“title”=>“php manual”,”editor”=>”X”,”author”=>”A”),

array(“title”=>“perl manual”,”editor”=>”Y”,”author”=>”B”),

array(“title=>“C manual”,”editor”=>”Z”,author=>”C”));

• Common loop

for ($i=0; $i < count($books); $i++ )

print “$i-st book, title: ”.$books[$i][“title”].” author: “.$books[$i][“author”].

“ editor: “.$books[$i][“editor”];

// Add .”\n” for text new page or “.<BR>” for HTML new page;

• Use list and each

for ($i=0; $i < count($books); $i++)

{

print “$i-st book is: “;

while ( list($key,$value) = each( $books[$i] ))

print “$key: $value ”;

print “<BR>”; // or “\n”

}

Page 16: PHP Scripting language

Arithmetic Operators

Example Name Result

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

$a - $b Subtraction $b subtractedfrom $a

$a * $b Multiplication Product of $aand $b

$a / $b Division Dividend of $aand $b

$a % $b Modulus Remainder of $adivided by $b

Page 17: PHP Scripting language

Logical Operators

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 Or True if either $a or $b is true, butnot 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

Page 18: PHP Scripting language

Comparison OperatorsExample Result

$a == $b True if both $a is equal to $b

$a != $b True if $a is not equal to $b

$a < $b True if $a is less than $b

$a > $b True if $a is greater than $b

$a <= $b True if $a is less than or equal $b

$a >= $b True if $a is greater than or equal$b

Page 19: PHP Scripting language

C-like syntax● For loops● While ● switch

casebreak

● ++ / --● elseif

Page 20: PHP Scripting language

LOOPING EXAMPLE <!--#! /usr/local/bin/php --> <html> <body> <h2>Radio buttons example</h2> <form> <table border=0> <tr> <th>Button</th><th>Text</th></tr> <?php for ($j=1; $j<6; $j++) {

$rbname = "rbn";$rbvalue = "rbv_".$j;$rbtext = "Text_".$j;$radio = "input type=\"radio\" name=\"$rbname\" value=\"$rbvalue\" " ;if ($j == 3) $radio .= " checked=\"checked\" ";echo "<tr><td align =\"center\"><$radio></td> <td>$rbtext</td></tr>";};

?></table>

</form></body></html>

Page 21: PHP Scripting language

Arrays

Construct arrays using the array() function:

$numbers = array(5,4,3,2,1)

$words = array(“Web”,”Database”,”Interactive”,”Apps”)

Numbered arrays: accessed by numeric indexDefault: Index of 1st element is 0.

Echo $words[0]; // Web Echo $words[3]; // Apps

$words() = “GUI”; // adds a 5th element to the above $words(5) = “Usability”; // adds 6th element

Page 22: PHP Scripting language

Associative Arrays

Also called string-indexed arrays

Uses key to access values stored in the array:

$catch_it[‘cat’] = “mouse”;$catch_it[‘dog’] = “cat”;

echo catch_it[‘dog’]; // prints “cat”

Page 23: PHP Scripting language

Array Example … <h2>Radio buttons array example</h2>

<form> <table border=0> <tr> <th>Button</th><th>Text</th></tr> <?php $pizza_type = array("Ham","Sausage","Pepperoni","Anchovies","Cheese");for ($j=1; $j<6; $j++) {

$rbname = "rbn";$rbvalue = "rbv_".$j;$rbtext = $pizza_type[$j -1];$radio = "input type=\"radio\" name=\"$rbname\" value=\"$rbvalue\"

" ;if ($j == 3) $radio .= " checked=\"checked\" ";echo "<tr><td align =\"center\"><$radio></td>

<td>$rbtext</td></tr>";};

?></table></form></body></html>

Page 24: PHP Scripting language

Form Handling (1)● Three methods

– Short: $varfoo (the variable name defined in the <FORM>)– Medium: $_POST[‘varfoo’], (recommended for versions of PHP +4.1)– Long: $HTTP_POST_VARS[‘varfoo’]

● Need register_globals ON for short method to work.If register_globals = on, the EGPCS (Environment, GET, POST, Cookie, Server) variables are regarded as global variables.

● Tip: For checkbox variables your variable name should end with [ ]– Checkbox results are automatically put into an array– Example: <input type=checkbox name=foo[] value=Y>

Page 25: PHP Scripting language

Form Handling (2)“action.php”● Traditional:

● Since PHP 4.2:

– Better: less danger for incorrect programs

“form.php”

Page 26: PHP Scripting language

PHP Variables from a Form<html><body><?phpif ( $name ) { print( "Hello, $name !");} else { // form entry print( "<form action=\"$PHP_SELF\" method=post>\n"); print( "Your name: <input type=text size=10 name=name ><br>\n"); print("<input type=submit value=Submit>\n" ); print("</form>\n");}?></body></html>

Page 27: PHP Scripting language

Passing variables via URLYou can test by setting variables through a URL:

http://localhost/php/urlvariables.php?var1=This+is+a+String&var2=3.1415159265

(urlvariables.php)<!--#! /usr/local/bin/php --><html><body><?php echo "$var1 <br>"; ?><?php echo "$var2 <br>";?></body></html>

Page 28: PHP Scripting language

Dates

Date and Time is carried in Unix timestamp:Number of seconds since 1 Jan 1970 GMT

To create a timestamp, use mktime():int mktime(int hour, int minute, int second,

int month, int day, int year [, int is_dst]

Ex: $aDate = mktime(9, 30,0,6,18,1998)9:30 A.M. on June 18, 1998

String to timestamp:$var = strtotime(“25 December 2002”)

Page 29: PHP Scripting language

Formatting a Date

Date() function:string date(string format, [int timestamp])

$var = mktime(8, 15, 25, 8, 24, 1964);

echo date(‘d/m/Y’,$var); // “24/08/1964”

echo date(‘m/d/y’,$var); // “08/24/64”

echo date(‘m/d/y); // “03/12/03” (today)

Many powerful formatting arguments: see the PHP on-line manual.

Page 30: PHP Scripting language

Other Functions

Absolute Value: echo abs(-1); // prints 1

Ceiling and Floor: integer above or below floatecho ceil(27.3); // prints 28echo floor(27.3); // prints 27

Rounding: Up or down value to given precisionecho round(10.4); // prints 10echo round(10.5); // prints 11echo round(2.40964,3); // prints 2.410

Page 31: PHP Scripting language

Random Number Generation

Random number generation: needs seeding

// generate a seed$seed = (float) srand(microtime() * 100000000;

// seed the random number generatorsrand($seed);

// generate random numbersecho rand(); // between 0 and getmaxrand()

echo rand(1,6); // random numbers between// 1 and 6, inclusive

Page 32: PHP Scripting language

User-Defined Functions<?php function doublevalue($var) {$returnVal = $var * 2;return($returnVal);}$var = 5;$temp = doublevalue($var);echo "$temp";?>

Page 33: PHP Scripting language

Syntax to define a function function function_name([parameters-list]opt)

{……implementation code……}

parameters-list is a sequence of variables separated by “,”

• it’s not allowed to overload the name of an existing function;• Function names aren’t case-sensitive; • To each parameter can be assigned a default value;• arguments can be passed by value or by reference• It’s possible using a variable number of parameters

Page 34: PHP Scripting language

Passing Arguments● Passing By Value: (outputs 5)

function square($p)

{ return $p*$p; }

$a=5;

echo square($a);● Passing By Reference: (outputs 25)

function square($p)

{ return $p*$p; }

$a=5;

echo square(&$a);

Page 35: PHP Scripting language

Variable Scope● Local and Global are the only options

● Variables defined within functions have scope local to that function.

● To access a global variable from within a function use the GLOBAL keyword:

function test()

{ global $a; echo $a; }

$a = “the quick brown fox”;

test();● Alternatively use $GLOBALS array:

function test()

{ echo $GLOBALS[“a”]; }

$a = “the quick brown fox”;

test();

Page 36: PHP Scripting language

Include FilesYou can put several functions into a file and save it:

<?php function doublevalue($var) {$returnVal = $var * 2;return($returnVal);}function bold($string){echo "<b>" . $string . "</b>\n";}?>Save this file as stdfunctions.inc

Page 37: PHP Scripting language

Using Include Files<html><body><?include "stdfunctions.inc";

echo "this is not bold <br>\n" ;bold("this is bold");echo "<br>again, this is not bold <br> \n";

bold(doublevalue(3.14));?></body></html>

Page 38: PHP Scripting language

File Access#cat /usr/local/myDatabaseDirectory/library.txt

php manual X A 330

perl manualY B 540

C manual Z C 480

(fields separated by tabs: 'php manual<tab>X<tab>A', new line at the end of each entry)

<? // script to show all book in my library

$books = file(“/usr/local/myDatabaseDirectory/library.txt”); // retrieve library “database”

for ($i=0; $i<count($books), $i++ )

$books_array[$i] = explode( “\t”, $books[$i]); // Extract elements from line

...

for ($i=0; $i<count($books_array), $i++ )

print “$i-st book, title: ”.$books_array[$i][“title”].” author: “.$books_array[$i][“author”].

“ editor: “.$books_array[$i][“editor”].”<BR>”;

Page 39: PHP Scripting language

Sessions● A session is the time a client spends on a site.

● A session id is stored (as a cookie) on the client OR passed along via the URLs (using php only). The id is a key to session information stored on the server for each client.

– Php sessions will work even if cookies have been disabled by the person using the browser

● Session information is stored on the server.

Page 40: PHP Scripting language

PHP Sessions● session_start(); called at each script using the session variables● $total = ….● $cart["pencils"] = $qty;● $cart[$productname] = $productqty;● session_register("total");● session_register("cart");● any other script, can use $cart and $total.● $result = session_is_registered("total");● session_unregister("total");● session_destroy();

Page 41: PHP Scripting language

Object Oriented PHP● Encapsulation● Polymorphism● Inheritance● Multiple Inheritance: actually unsupported

Page 42: PHP Scripting language

Encapsulation<?

class dayOfWeek {

var $day,$month,$year;

function dayOfWeek($day,$month,$year) {

$this->day = $day;

$this->month = $month;

$this->year = $year;

}

function calculate(){

if ($this->month==1){

$monthTmp=13;

$yearTmp = $this->year - 1;

}

if ($this->month == 2){

$monthTmp = 14;

$yearTmp = $this->year - 1;

}

$val4 = (($month+1)*3)/5;

$val5 = $year/4;

$val6 = $year/100;

$val7 = $year/400;

$val8 = $day+($month*2)+$val4+$val3+$val5-$val6+$val7+2;

$val9 = $val8/7;

$val0 = $val8-($val9*7);

return $val0;

}

}

// Main

$instance =

new dayOfWeek($_GET[“day”],$_GET[“week”],$_GET[“ month”]);

print “You born on “.$instance->calculate().”\n”;

?>

Page 43: PHP Scripting language

Allow the creation of a hierarchy of classes

Inheritance

Class reuseMe {

function reuseMe(){...}

function doTask1(){...}

function doTask2(){...}

function doTask3(){...}

}

Class extends reuseMe {

function example(){ ... // local initializations // call super constructor reuseMe::reuseMe(); }

function doTask4(){...}

function doTask5(){...}

function doTask6(){...} }

Page 44: PHP Scripting language

Polymorphism

Class extends reuseMe {

function example(){ ... // local initializations // call super constructor reuseMe::reuseMe(); }

function doTask4(){...}

function doTask5(){...}

function doTask6(){...}

function doTask3(){...} }

class reuseMe {

function reuseMe(){...}

function doTask1(){...}

function doTask2(){...}

function doTask3(){...}

}

A member function can override superclass implementation. Allow each subclass to reimplement a common interfaces.

Page 45: PHP Scripting language

Class exampleclass Cart

{

var $items; // Items in our shopping cart

// Add $num articles of $artnr to the cart

function add_item ($artnr, $num)

{

$this->items[$artnr] += $num;

}

// Take $num articles of $artnr out of the cart

function remove_item ($artnr, $num)

{

if ($this->items[$artnr] > $num) {

$this->items[$artnr] -= $num;

return true;

} else {

return false;

}

}

}

Page 46: PHP Scripting language

Inheritance exampleClass ParentObject {    var $value;

  function ParentObject() {        $this->value = 42;   } } class MemberObject extends ParentObject {    var $string;

   function MemberObject() {       $this->string = "This is a test string."; $this->ParentObject();   } } class ObjTest {    var $ObjPointer;

  function ObjTest() {        $tmp = new MemberObject; $this->ObjPointer = $tmp;   } } $object = new ObjTest; echo "String Contents: " . $object->ObjPointer->string . "\n"; echo "Value  Contents: " . $object->ObjPointer->value . "\n";

Page 47: PHP Scripting language

Multiple Inheritance not actually supported by PHP

class extends reuseMe1,reuseMe2 {...}

class reuseMe1 { function reuseMe1(){...} function doTask1(){...} function doTask2(){...} function doTask3(){...}

}

class reuseMe2 { function reuseMe2(){...} function doTask3(){...} function doTask4(){...} function doTask5(){...}

}

Page 48: PHP Scripting language

Overview of MySQL● Relational database management system (RDBMS)

● Free

● Website @ http://www.mysql.com/

Page 49: PHP Scripting language

MySQL Basics● Common SQL Statements

– INSERT

– SELECT

– UPDATE

– DELETE

● Simple Join

● Entity-Relationship (ER) Modeling

● An Easy Way to Manage Your MySQL DBs

Page 50: PHP Scripting language

MySQL Basics (cont.)● A relational database manager (MySQL) manages

databases which holds tables which has records (rows) with attributes (columns)

● Each record must have a unique ID, also known as a Primary Key. When used as an identifier in another table it’s called a Foreign Key. Used for joins.

● Each attribute has to have a data type. (e.g. int, text, varchar)

● A database language (SQL) is used to create and delete databases and manage data

Page 51: PHP Scripting language

CREATE TABLE

● Table structure for following examples:

● Created two tables, ‘oscarpool’ & ‘bestdirector’

CREATE TABLE oscarpool ( uid int(4) auto_increment, username varchar(255), email varchar(255), bestpicture int(2), PRIMARY KEY (uid))

CREATE TABLE bestdirector ( bdid int(4) auto_increment, name varchar(255), PRIMARY KEY (bdid))

Page 52: PHP Scripting language

INSERT● Common SQL Statement: INSERT

INSERT INTO

oscarpool

(username,email,bestpicture)

VALUES

(‘dolsen',‘[email protected]',1)

● Creates a new record in the table ‘oscarpool’● Text fields need to have ‘s.● Tip: If you have an ‘ in your data you need to escape it before inserting it.

Can use the PHP function addslashes().

Example: ‘John O\’Brien’

Page 53: PHP Scripting language

SELECT● Common SQL Statement: SELECT

SELECT

uid,username

FROM

oscarpool

● Selects the attributes ‘uid’ and ‘username’ from every record in ‘oscarpool’● SELECT is how you query the database. You can also:

– limit the number of records returned with LIMIT, – limit retrieval to those records that match a condition with WHERE,– sort the data after the query has been evaluated using ORDER BY

● Tip: To easily select every attribute replace ‘uid’ with ‘*’

Page 54: PHP Scripting language

UPDATE● Common SQL Statement: UPDATE

UPDATE

oscarpool

SET

email = ‘[email protected]

WHERE

uid = 1

● Updates the email address where ‘uid = 1’ in the table ‘oscarpool’● In this case I know that uid 1 is what my record was. In many

cases you’d pass a uid variable from a form.

Page 55: PHP Scripting language

DELETE● Common SQL Statement: DELETE

DELETE FROM

oscarpool

WHERE

uid = 1

● Deletes the record where ‘uid = 1’ in the table ‘oscarpool’● DELETE only removes the record from the table. To remove an entire

table from the database you need to use the SQL statement DROP.● Tip: To remove every record in a table but not remove the table just

don’t include the WHERE clause.

Page 56: PHP Scripting language

JOIN● Simple Join

SELECT

bd.name

FROM

oscarpool op, bestdirector bd

WHERE

op.uid = 1 and

op.bestdirector = bd.bdid

● Selects the name of the Best Director that the user with ‘uid = 1’ has chosen

● bestdirector is a Foreign Key of the Primary Key for the table BestDirector

● Tip: Try to not have fields from two different tables have the same name. Gets confusing when trying to output this data when we connect with PHP.

Page 57: PHP Scripting language

Entity-Relationship (ER) Modeling● ER Modeling is the simple and clear method of expressing the design

(relations) of a database between tables and attributes.Rectangles – Represent entities.

Diamonds – Represent relationships

between entities

Ellipses – Represent attributes that

describe an entity

Lines – Connect entities to relationships.

Can have annotation.

M = many, 1 = one.

Lines – Connects entities to attributes. No annotation.

● Entity = Table, Attributes = Attributes● Web Database Applications by O’Reilly Publishers gives decent overview

Page 58: PHP Scripting language

Using MySQL● An easy way to manage your DBs● phpMyAdmin is a browser-based administration tool for MySQL. Needs to

be installed on your server.● It can:

– create and drop databases

– create, copy, drop, rename and alter tables

– delete, edit and add fields

– manage keys on fields

– load text files into tables

– create (*) and read dumps of tables

– and more

● Download phpMyAdmin @ http://www.phpmyadmin.net/

Page 59: PHP Scripting language

A Query Example● Connect to the database

requires: username, password, dbname and host

● Select a database● Send a query● Loop through the results (optional)

Page 60: PHP Scripting language

Another Query Example<html>

<body>

<h1>A List of Users Who Have Signed Up For OscarPool</h1>

<?

$dbh = mysql_connect("localhost",“dbusername",“dbpassword")

or die(“Couldn't connect to database.");

$db = mysql_select_db(“dbname", $dbh)

or die(“Couldn't select database.");

$sql = “SELECT username, email FROM oscarpool”;

$result = mysql_query($sql, $dbh)

or die(“Something is wrong with your SQL statement.");

while ($row = mysql_fetch_array($result)) {

$username = $row[‘username’];

$email = $row[‘email’];

echo ‘<a href=“mailto:’.$email.’”>’.$username.’</a><br />\n’;

}

?>

</body>

</html>

Page 61: PHP Scripting language

Notes for previous example● The first option in mysql_connect can be an IP address.● mysql_query returns a small table with your results in it. The while loop

then goes through each record of that small table and pulls out the attributes/fields you selected in your SQL statement.

● die( ) will kill the script. Make sure that that text is informative.● If you use a function in your SQL query then it has to be a part of the

$row statement. For example, UNIX_TIMESTAMP(datefield) would be $row[‘UNIX_TIMESTAMP(datefield)’]

● \n stands for a new line so that your source code will look a little neater:● PHP MySQL functions @

url: http://www.php.net/manual/en/ref.mysql.php