PHP Miscellaneous Dr. E. Benoist Winter Term 2005-2006 PHP - - PowerPoint PPT Presentation

php miscellaneous
SMART_READER_LITE
LIVE PREVIEW

PHP Miscellaneous Dr. E. Benoist Winter Term 2005-2006 PHP - - PowerPoint PPT Presentation

Berner Fachhochschule - HTI PHP Miscellaneous Dr. E. Benoist Winter Term 2005-2006 PHP Miscellaneous 1 PHP Miscellaneous Generating PDF Documents FPDF Library Image Generation GD Library Example: Barcode Generator Authorization


slide-1
SLIDE 1

Berner Fachhochschule - HTI

PHP Miscellaneous

  • Dr. E. Benoist

Winter Term 2005-2006

PHP Miscellaneous 1

slide-2
SLIDE 2

PHP Miscellaneous

  • Generating PDF Documents

FPDF Library

  • Image Generation

GD Library Example: Barcode Generator

  • Authorization

Using HTTP Using HTML form

  • Template
  • Web Services
  • Conclusion

PHP Miscellaneous 2

slide-3
SLIDE 3

Miscellaneous functionalities of PHP

Generate Portable Document Format (PDF) Files

◮ Two Libraries ◮ PDFLib: A C library that must be included at compilation

time (not free for commercial use);

◮ fpdf: A free, PHP written, PDF library.

Authentification

◮ Use HTTP authentification scheme (which open a small

pop-up);

◮ Create your own authentification scheme using forms.

Image Generation

◮ Use the GD library, a C written lib included durring the

compilation

◮ Creation of jpeg and png files (no gif support for rights

problems)

PHP Miscellaneous 3

slide-4
SLIDE 4

FPDF library

Freely downloadable

◮ http://www.fpdf.org/ ◮ In PHP written ◮ Contains a PHP class: FPDF ◮ Needs to be copied in the directory where PHP can find it ◮ Contains also font metrics (should be in a fonts subdirectory

in the same directory. Functionalities

◮ Creates a PDF document and makes the output ◮ Insert text, images, headers and footers ◮ Defines page size (A4, letter, landscape or portrait) ◮ Change the margins ◮ . . .

PHP Miscellaneous Generating PDF Documents: FPDF Library 4

slide-5
SLIDE 5

Create your first document

Initialize and use the FPDF object

◮ Load the class ◮ Create an instance of this class $pdf=new FPDF();

  • Can be more explicit: $pdf=new FPDF(’P’’mm’,’A4’);,
  • ’P’ stands for portrait, could be ’L’
  • ’mm’ stands for millimeters, could be cm, in or pt
  • The format could be Letteror Legal

◮ Create a new page $pdf->AddPage(); ◮ Write a message

$pdf−>SetFont(’Arial’,’B’,16); $pdf−>Cell(40,10,’Hello World!’);

◮ Change the header and write the content of the document

$pdf->Output();

PHP Miscellaneous Generating PDF Documents: FPDF Library 5

slide-6
SLIDE 6

Create your first document (Cont.)

Example <?php require(’../fpdf.php’); $pdf=new FPDF(); $pdf−>AddPage(); $pdf−>SetFont(’Arial’,’B’,16); $pdf−>Cell(40,10,’Hello World!’); $pdf−>Output(); ?>

PHP Miscellaneous Generating PDF Documents: FPDF Library 6

slide-7
SLIDE 7

Write Header and Footer

1 <?php 2 require(’../fpdf.php’); 3 class PDF extends FPDF 4 { 5 function Header() { 6 $this−>Image(’logo pb.png’,10,8,33); 7 $this−>SetFont(’Arial’,’B’,15); 8 //Move to the right 9 $this−>Cell(80); 10 //Title 11 $this−>Cell(30,10,’Title’,1,0,’C’); 12 //Line break 13 $this−>Ln(20); 14 }

PHP Miscellaneous Generating PDF Documents: FPDF Library 7

slide-8
SLIDE 8

Write Header and Footer (Cont.)

15 //Page footer 16 function Footer() 17 { 18 //Position at 1.5 cm from bottom 19 $this−>SetY(−15); 20 $this−>SetFont(’Arial’,’I’,8); 21 $this−>Cell(0,10,’Page ’.$this−>PageNo().’/{nb}’,0,0,’C’); 22 } 23 } 24 $pdf=new PDF(); 25 $pdf−>AliasNbPages(); 26 $pdf−>AddPage(); 27 $pdf−>SetFont(’Times’,’’,12); 28 for($i=1;$i<=40;$i++) 29 $pdf−>Cell(0,10,’Printing line number ’.$i,0,1); 30 $pdf−>Output(); 31 ?>

PHP Miscellaneous Generating PDF Documents: FPDF Library 8

slide-9
SLIDE 9

Insert Header and Footer (Cont.)

Header

◮ Overwrite the Header() function, ◮ Insert an image $this->Image(’logo_pb.png’10,8,33); , ◮ Move to the right $this->Cell(80); ◮ Line break of 20mm $this->Ln(20);

Footer

◮ Overwrite the Footer() function, ◮ Position at 1.5 cm from bottom $this->SetY(-15); ◮ Includes the page number:

$pdf−>AliasNbPages(); $pdf−>AddPage();

PHP Miscellaneous Generating PDF Documents: FPDF Library 9

slide-10
SLIDE 10

Add color in the cells

A cell can have 3 colors

◮ Draw color for the rectangle (is set if we define a width) ◮ Fill color for the inside ◮ Text color for text

$this−>SetDrawColor(0,80,180); $this−>SetFillColor(230,230,0); $this−>SetTextColor(220,50,50); //Thickness of frame (1 mm) $this−>SetLineWidth(1); $this−>Cell($width,9,$title,1,1,’C’,1);

PHP Miscellaneous Generating PDF Documents: FPDF Library 10

slide-11
SLIDE 11

Parameters of a Cell

Compute the width of a text $w=$this−>GetStringWidth($title); A Cell can be configured $this−>Cell($width,9,$title,1,1,’C’,1);

◮ width ◮ height ◮ text ◮ if borders should be drawn ◮ where the current position moves after it

(to the right, below or to the beginning of the next line)

◮ If the text is centered (C) or aligned ◮ Fill or not fill (boolean)

To output justified text $this−>MultiCell(0,5,$txt);

PHP Miscellaneous Generating PDF Documents: FPDF Library 11

slide-12
SLIDE 12

Multicolumn Output

1 //Current column 2 var $col=0; 3 //Ordinate of column start 4 var $y0; 5 function Header() 6 { 7 ... 8 $this−>y0=$this−>GetY(); 9 } 10 11 function SetCol($col) 12 { 13 //Set position at a given column 14 $this−>col=$col; 15 $x=10+$col∗65; 16 $this−>SetLeftMargin($x); 17 $this−>SetX($x); 18 }

PHP Miscellaneous Generating PDF Documents: FPDF Library 12

slide-13
SLIDE 13

Multicolumn Output (Cont.)

19 function AcceptPageBreak() { 20 //Method accepting or not automatic page break 21 if($this−>col<2) { 22 //Go to next column 23 $this−>SetCol($this−>col+1); 24 //Set ordinate to top 25 $this−>SetY($this−>y0); 26 //Keep on page 27 return false; 28 } 29 else{ 30 //Go back to first column 31 $this−>SetCol(0); 32 //Page break 33 return true; 34 } 35 } 36 //Output text in a 6 cm width column 37 $this−>MultiCell(60,5,$txt);

PHP Miscellaneous Generating PDF Documents: FPDF Library 13

slide-14
SLIDE 14

Create a table

A very basic one function BasicTable($header,$data) { //Header foreach($header as $col) $this−>Cell(40,7,$col,1); $this−>Ln(); //Data foreach($data as $row) { foreach($row as $col) $this−>Cell(40,6,$col,1); $this−>Ln(); } }

PHP Miscellaneous Generating PDF Documents: FPDF Library 14

slide-15
SLIDE 15

An improved table

Supports the following improvements

◮ Each column has its own width, ◮ Titles are centered ◮ Figures right aligned. ◮ Horizontal lines have been removed. (Left and Right LR are

shown)

PHP Miscellaneous Generating PDF Documents: FPDF Library 15

slide-16
SLIDE 16

An improved table (Cont.)

function ImprovedTable($header,$data) { //Column widths $w=array(40,35,40,45); for($i=0;$i<count($header);$i++) //Header $this−>Cell($w[$i],7,$header[$i],1,0,’C’); $this−>Ln(); foreach($data as $row) { $this−>Cell($w[0],6,$row[0],’LR’); $this−>Cell($w[1],6,$row[1],’LR’); $this−>Cell($w[2],6,number format($row[2]),’LR’,0,’R’); $this−>Cell($w[3],6,number format($row[3]),’LR’,0,’R’); $this−>Ln(); } $this−>Cell(array sum($w),0,’’,’T’); }

PHP Miscellaneous Generating PDF Documents: FPDF Library 16

slide-17
SLIDE 17

Insert Text

The Write() method

◮ $pdf->Write(5,’Hello World’); ◮ Goes to the end of the line ◮ Current position moves at the end of the text ◮ We can mix up text styles

PHP Miscellaneous Generating PDF Documents: FPDF Library 17

slide-18
SLIDE 18

Insert Links

Links inside a page

◮ Creates a link and write it

$link=$pdf−>AddLink(); $pdf−>Write(5,’here’,$link);

◮ Where does it go:

$pdf−>SetLink($link); Get external URL $pdf−>Image(’logo.png’,10,10,30,0,’’,’http://www.fpdf.org’);

PHP Miscellaneous Generating PDF Documents: FPDF Library 18

slide-19
SLIDE 19

PHP and Image Generation

What for?

◮ HTTP allows programmers to generate anything as response. ◮ It is possible to generate images for Maps, Menu items, ...

How to create images?

◮ Use the GD Library. GD library is a C library that allows

programmers to create images. Actually GD library implements JPEG and PNG standards.

◮ Compile the PHP module with the GD library, ◮ Write scripts that create images.

PHP Miscellaneous Image Generation: GD Library 19

slide-20
SLIDE 20

Example

Create an image 50 x 100 <?php // Create a new image (50 x 100) $im = @ImageCreate (50, 100)

  • r die (”Cannot Initialize new GD image stream”);

// Set background color to white $background color = ImageColorAllocate ($im, 255, 255, 255); // Set the pen color $text color = ImageColorAllocate ($im, 233, 14, 91); // Write a string in the image ImageString ($im, 1, 5, 5, ”A Simple Text String”, $text color); // Write out a header for the HTTP and then the image header (”Content−type: image/png”); ImagePNG ($im); ?>

PHP Miscellaneous Image Generation: GD Library 20

slide-21
SLIDE 21

Mime types

Content type must contain a valid mime type if (function exists(”imagegif”)) { Header(”Content−type: image/gif”); ImageGIF($im); } elseif (function exists(”imagejpeg”)) { Header(”Content−type: image/jpeg”); ImageJPEG($im, ””, 0.5); } elseif (function exists(”imagepng”)) { Header(”Content−type: image/png”); ImagePNG($im); } elseif (function exists(”imagewbmp”)) { Header(”Content−type: image/vnd.wap.wbmp”); ImageWBMP($im); } else{ die(”No image support in this PHP server”); }

PHP Miscellaneous Image Generation: GD Library 21

slide-22
SLIDE 22

Create Images

ImageCreate int imagecreate (int x size, int y size) ImageCreate() returns an image identifier representing a blank image of size x size by y size. ImageCreateFromGIF int imagecreatefromgif (string filename) ImageCreateFromGif() returns an image identifier representing the image obtained from the given filename or URL. ImageCreateFromJPEG ImageCreateFromWBMP

PHP Miscellaneous Image Generation: GD Library 22

slide-23
SLIDE 23

Create Images (Cont.)

ImageCreateFromPNG int imagecreatefrompng (string filename) ImageCreateFromPNG() returns an image identifier representing the image obtained from the given filename or URL. ImageCreateFromPNG() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error PNG:

PHP Miscellaneous Image Generation: GD Library 23

slide-24
SLIDE 24

Create Images (Cont.)

Example to handle an error during creation (courtesy vic@zymsys.com) function LoadPNG ($imgname) { $im = @ImageCreateFromPNG ($imgname); /∗ Attempt to open ∗/ if (!$im) { /∗ See if it failed ∗/ $im = ImageCreate (150, 30); /∗ Create a blank image ∗/ $bgc = ImageColorAllocate ($im, 255, 255, 255); $tc = ImageColorAllocate ($im, 0, 0, 0); ImageFilledRectangle ($im, 0, 0, 150, 30, $bgc); /∗ Output an errmsg ∗/ ImageString ($im, 1, 5, 5, ”Error loading $imgname”, $tc); } return $im; }

PHP Miscellaneous Image Generation: GD Library 24

slide-25
SLIDE 25

Draw a String

ImageString Draw a string horizontally int imagestring (int im, int font, int x, int y, string s, int col) ImageString() draws the string s in the image identified by im at coordinates x, y (top left is 0, 0) in color col. If font is 1, 2, 3, 4

  • r 5, a built-in font is used.

ImageStringUp Draw a string vertically int imagestringup (int im, int font, int x, int y, string s, int col) ImageStringUp() draws the string s vertically in the image identified by im at coordinates x, y (top left is 0, 0) in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.

PHP Miscellaneous Image Generation: GD Library 25

slide-26
SLIDE 26

Draw a String (Cont.)

ImageLoadFont int imageloadfont (string file) ImageLoadFont() loads a user-defined bitmap font and returns an identifier for the font (that is always greater than 5, so it will not conflict with the built-in fonts). The font file format is currently binary and architecture dependent. You can get more info at http://www.boutell.com/gd/

PHP Miscellaneous Image Generation: GD Library 26

slide-27
SLIDE 27

Make drawings

int imagerectangle (int im, int x1, int y1, int x2, int y2, int col) ImageRectangle() creates a rectangle of color col in image im starting at upper left coordinate x1, y1 and ending at bottom right coordinate x2, y2. 0, 0 is the top left corner of the image. int imageline (int im, int x1, int y1, int x2, int y2, int col) ImageLine() draws a line from x1, y1 to x2, y2 (top left is 0, 0) in image im of color col. int imagesetpixel (int im, int x, int y, int col) ImageSetPixel() draws a pixel at x, y (top left is 0, 0) in image im of color col.

PHP Miscellaneous Image Generation: GD Library 27

slide-28
SLIDE 28

Make drawings (Cont.)

ImagePolygon int imagepolygon (int im, array points, int num points, int col) ImagePolygon() creates a polygon in image im. Points is a PHP array containing the polygon’s vertices, ie. points[0] = x0, points[1] = y0, points[2] = x1, points[3] = y1, etc. Num points is the total number of vertices. ImageFilledRectangle ImageFilledPolygon . . .

PHP Miscellaneous Image Generation: GD Library 28

slide-29
SLIDE 29

Example

Create images with TTF fonts

◮ Must be enabled durring the compilation ◮ Requires FreeTypes fonts

// Start the random gizmo srand((double)microtime()∗1234567); // Get a background $image = imagecreatefromjpeg(rand(1,exec(’ls ∗.jpg | wc −l’)) . ”.jpg”); $font = rand(1,exec(’ls ∗.ttf | wc −l’)) . ”.ttf”; // Get a font $textcolor = imagecolorallocate($image,0,0,0); // Set text color $text1 = ”Hello World”; // Here is our text // Write the text with a font imagettftext($image, 50, 0, 20, 50, $textcolor, $font, $text1); header(”Content−type: image/jpeg”); // Its a JPEG imagejpeg($image,’’,90); // Zap it to the browser imagedestroy($image); // Memory Management

PHP Miscellaneous Image Generation: GD Library 29

slide-30
SLIDE 30

Barcode Generator

<?php function UPCAbarcode($code) { $lw = 2; $hi = 100; $Lencode = array(’0001101’,’0011001’,’0010011’,’0111101’,’0100011’, ’0110001’,’0101111’,’0111011’,’0110111’,’0001011’); $Rencode = array(’1110010’,’1100110’,’1101100’,’1000010’,’1011100’, ’1001110’,’1010000’,’1000100’,’1001000’,’1110100’); $ends = ’101’; $center = ’01010’; /∗ UPC−A Must be 11 digits, we compute the checksum. ∗/ if ( strlen($code) != 11 ) { die(”UPC−A Must be 11 digits.”); } /∗ Compute the EAN−13 Checksum digit ∗/ $ncode = ’0’.$code; $even = 0; $odd = 0; for ($x=0;$x<12;$x++) { if ($x % 2) { $odd += $ncode[$x]; } else { $even += $ncode[$x]; } } $code.=(10 − (($odd ∗ 3 + $even) % 10)) % 10;

PHP Miscellaneous Image Generation: Example: Barcode Generator 30

slide-31
SLIDE 31

Barcode Generator (Cont.)

/∗ Create the bar encoding using a binary string ∗/ $bars=$ends; $bars.=$Lencode[$code[0]]; for($x=1;$x<6;$x++) { $bars.=$Lencode[$code[$x]]; } $bars.=$center; for($x=6;$x<12;$x++) { $bars.=$Rencode[$code[$x]]; } $bars.=$ends; /∗ Generate the Barcode Image ∗/ $img = ImageCreate($lw∗95+30,$hi+30); $fg = ImageColorAllocate($img, 0, 0, 0); $bg = ImageColorAllocate($img, 255, 255, 255); ImageFilledRectangle($img, 0, 0, $lw∗95+30, $hi+30, $bg); $shift=10;

PHP Miscellaneous Image Generation: Example: Barcode Generator 31

slide-32
SLIDE 32

Barcode Generator (Cont.)

for ($x=0;$x<strlen($bars);$x++) { if (($x<10) || ($x>=45 && $x<50) || ($x >=85)) { $sh=10; } else { $sh=0; } if ($bars[$x] == ’1’) { $color = $fg; } else { $color = $bg; } ImageFilledRectangle($img, ($x∗$lw)+15,5,($x+1)∗$lw+14,$hi+5+$sh,$color); } /∗ Add the Human Readable Label ∗/ ImageString($img,4,5,$hi−5,$code[0],$fg); for ($x=0;$x<5;$x++) { ImageString($img,5,$lw∗(13+$x∗6)+15,$hi+5,$code[$x+1],$fg); ImageString($img,5,$lw∗(53+$x∗6)+15,$hi+5,$code[$x+6],$fg); } ImageString($img,4,$lw∗95+17,$hi−5,$code[11],$fg); /∗ Output the Header and Content. ∗/ header(”Content−Type: image/png”); ImagePNG($img); } UPCAbarcode(’12342678901’); ?>

PHP Miscellaneous Image Generation: Example: Barcode Generator 32

slide-33
SLIDE 33

Authorization

Using HTTP Authorization scheme

◮ Scripts asks for a login (401 error) ◮ Browser answers a username password pair ◮ If it is OK: login ◮ If not: 401 Error (another login prompt is sent)

<?php if(!isset($ SERVER[’PHP AUTH USER’]) || $ SERVER[’PHP AUTH USER’] !=’bie’){ header(”HTTP/1.0 401 Unauthorized”); header(’WWW−AUthenticate: Basic realm=”My Realm”’); $msg= ”You are not authorized to access to this page”; } else{ $msg = <<<MSG Hello {$ SERVER[’PHP AUTH USER’]}<br> Your password is:{$ SERVER[’PHP AUTH PW’]} MSG; } ?>

PHP Miscellaneous Authorization: Using HTTP 33

slide-34
SLIDE 34

Write your own HTML form

Use a form

◮ Send a form ◮ if the form has been filled, test the value ◮ if the value is OK, insert username as a session value ◮ Only test session value username to check if user is loged in.

PHP Miscellaneous Authorization: Using HTML form 34

slide-35
SLIDE 35

HTML form (Cont.)

<?php session start(); $login form = <<<END <form method=”POST”> Username <input type=”text” name=”username”><br> Password <input type=”password” name=”password”> <br> <input type=”submit” value=”Logg−in”> </form><br> END; if(isset($ POST[’username’])&&isset($ POST[’password’])){ if($ POST[’username’] ==’bie’ && $ POST[’password’] == ’bie’){ $ SESSION[’username’]=$ POST[’username’]; } else{ $login form .= ”Wrong username/password couple<br>\n”; } }

PHP Miscellaneous Authorization: Using HTML form 35

slide-36
SLIDE 36

HTML form (Cont.)

if(isset($ SESSION[’username’])){ $content = ”Hello {$ SESSION[’username’]} <br>\n”; $content .= ”<a href=\”logout.php\”>logout</a><br>”; } else{ $content = $login form; } ?> <html><header><title>Login form</title></header> <body> <?php echo $content; ?> </body> </html>

PHP Miscellaneous Authorization: Using HTML form 36

slide-37
SLIDE 37

Logout

Should allow the user to change user or deactivate the session <?php session start(); if(!isset($ SESSION[’username’])){ echo ”You were not loged in”; } else{ session unregister(’username’); echo ”You have been loged out.”; } ?>

PHP Miscellaneous Authorization: Using HTML form 37

slide-38
SLIDE 38

Template

Why Templates

◮ Separate design from programs ◮ Let two teams work independently ◮ needs to be physically separated

The PEAR HTML template IT

◮ Gratis on the net:

http://pear.php.net/package/HTML_Template_IT/

◮ Easy to understand ◮ Not too powerfull but easy to understand

PHP Miscellaneous Template 38

slide-39
SLIDE 39

Our first template

Contains comments marking a “block” <html> <head></head> <body> <!−− BEGIN main −−> Question: {QUESTION} <br /> Answer: {ANSWER} <!−− END main −−> </body> </html>

PHP Miscellaneous Template 39

slide-40
SLIDE 40

Principle

In the HTML file

◮ We define blocks

<!−− BEGIN main −−> ... <!−− END main −−>

◮ We define fields to be replaced

Question: {QUESTION} <br /> Answer: {ANSWER} In the PHP file

◮ We visit the blocks ◮ And affect variables

PHP Miscellaneous Template 40

slide-41
SLIDE 41

Example of PHP file

In PHP, we affect the variables <?php // include class require (’HTML/Template/IT.php’); // create object // set template directory $template = new HTML Template IT(”./”); // load template $template−>loadTemplateFile(”quiz.tpl”); // set block $template−>setCurrentBlock(”main”); // assign values $template−>setVariable(”QUESTION”, ”Knock, knock!”); $template−>setVariable(”ANSWER”, ”Who’s there?”); // parse block $template−>parseCurrentBlock(); // render page $template−>show(); ?>

PHP Miscellaneous Template 41

slide-42
SLIDE 42

Use multiple template

◮ You can use templates for recurring items (Footer, Header, Menu) ◮ You can load templates one after the other

$template = new HTML Template IT(”.”); // load template $template−>loadTemplateFile(”header.tpl”); ... $template−>parseCurrentBlock(); $template−>show(); // parse main block $template−>loadTemplateFile(”mainTemplate.tpl”); .. $template−>parseCurrentBlock(); $template−>show(); // parse footer $template−>loadTemplateFile(”footer.tpl”); ... $template−>parseCurrentBlock(); $template−>show();

PHP Miscellaneous Template 42

slide-43
SLIDE 43

Nested Blocks

Define a block inside another block

◮ For tables (TD’s inside TR’s) ◮ For lists

<!−− BEGIN main −−> <html> <head><basefont face=”{FONT}”></head> <body> <!−− BEGIN content −−> <h2>{TITLE}</h2> <img src=”{IMG}” align=”center”> <br /> {DESC} <!−− END content −−> </body> </html> <!−− END main −−>

PHP Miscellaneous Template 43

slide-44
SLIDE 44

Nested Blocks (Cont.)

◮ Visit the inner block, affect variables ◮ Then do the same for the outer block

// set values for inner block $template−>setCurrentBlock(”content”); $template−>setVariable(”TITLE”, ”Images >> Singapore”); $template−>setVariable(”IMG”, ”/images/galleries/singapore/01.jpg”); $template−>setVariable(”DESC”, ”Shopping at the biggest mall in Singapore...”); $template−>parseCurrentBlock(); // set values for outer block $template−>setCurrentBlock(”main”); $template−>setVariable(”FONT”, ”Arial”); $template−>parseCurrentBlock(); // show page $template−>show();

PHP Miscellaneous Template 44

slide-45
SLIDE 45

Iterate over Blocks

Display the content of an array

◮ Use a nested template

<html> <head> </head> <body> <!−− BEGIN list −−> <ul> <!−− BEGIN list item −−> <li>{ITEM} <!−− END list item −−> </ul> <!−− END list −−> </body> </html>

PHP Miscellaneous Template 45

slide-46
SLIDE 46

Iterate over Blocks

The corresponging PHP file $template−>loadTemplateFile(”list.tpl”); // set values for inner block $template−>setCurrentBlock(”list item”); $template−>setVariable(”ITEM”, ”Item A”); $template−>parseCurrentBlock(); $template−>setVariable(”ITEM”, ”Item B”); $template−>parseCurrentBlock(); $template−>setVariable(”ITEM”, ”Item C”); $template−>parseCurrentBlock(); $template−>setVariable(”ITEM”, ”Item D”); $template−>parseCurrentBlock(); // parse outer block $template−>parse(”list”); // render page $template−>show();

PHP Miscellaneous Template 46

slide-47
SLIDE 47

Iterate using a loop

The template <html> <table border> <!−− BEGIN row −−> <tr> <!−− BEGIN cell −−> <td> {DATA} </td> <!−− END cell −−> </tr> <!−− END row −−> </table> </html>

PHP Miscellaneous Template 47

slide-48
SLIDE 48

Iterate using a loop

require once ”HTML/Template/IT.php”; $data = array ( ”0” => array(”Stig”, ”Bakken”), ”1” => array(”Martin”, ”Jansen”), ”2” => array(”Alexander”, ”Merz”) ); $tpl = new HTML Template IT(”.”); $tpl−>loadTemplatefile(”main.tpl”, true, true); foreach($data as $name) { foreach($name as $cell) { // Assign data to the inner block $tpl−>setCurrentBlock(”cell”) ; $tpl−>setVariable(”DATA”, $cell) ; $tpl−>parseCurrentBlock(”cell”) ; } // Assign data and the inner block to the // outer block $tpl−>setCurrentBlock(”row”) ; $tpl−>parseCurrentBlock(”row”) ; } $tpl−>show();

PHP Miscellaneous Template 48

slide-49
SLIDE 49

PHP and Web services

◮ SOAP is a Web protocol ◮ It is used to transfer information ◮ Crossplatform and Cross-language

Support for .NET, Java, PHP, Flash, . . .

◮ Compatible with most of the firewalls ◮ XML over HTTP

PHP Miscellaneous Web Services 49

slide-50
SLIDE 50

Web Service?

◮ Web Service Description Language (WSDL)

XML file for describing the service (all methods parameters and return value)

◮ SOAP Request

<soap:Envelope xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/” xmlns:tns=”http://www.webservicex.net” xmlns:xs=”http://www.w3.org/2001/XMLSchema”> − <soap:Body> − <tns:Translate> − <tns:LanguageMode>EnglishTOFrench</tns:LanguageMode> − <tns:Text>This is a phrase</tns:Text> </tns:Translate> </soap:Body> </soap:Envelope>

PHP Miscellaneous Web Services 50

slide-51
SLIDE 51

Web Service? (Cont.)

◮ SOAP Response

<soap:Envelope xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/” xmlns:xsi=”http://www.w3.org/2001/XMLSchema−instance” xmlns:xsd=”http://www.w3.org/2001/XMLSchema”> <soap:Body> <TranslateResponse xmlns=”http://www.webservicex.net”> <TranslateResult>C est un essai</TranslateResult> </TranslateResponse> </soap:Body> </soap:Envelope>

PHP Miscellaneous Web Services 51

slide-52
SLIDE 52

Soap Client Class

◮ Create an object of class SoapClient ◮ Loads WSDL and create methods for each SOAP method

try{ $wsdl=”http://www.webservicex.com/TranslateService.asmx?WSDL”; $service = new SoapClient($wdsl); echo ”uses Soap version {$service−> soap version} <br>\n”; foreach ($service−> getFunctions() as $func){ echo ”$func <br>\n”; } } catch (SoapFault $ex){ echo ”Error opening the connection {$ex−>faultsting}”; }

PHP Miscellaneous Web Services 52

slide-53
SLIDE 53

Run a method

Parameters are sent in an array. try{ $wsdl=”http://www.webservicex.com/TranslateService.asmx?WSDL”; $translation = new SoapClient($wsdl); $parameters = array(LanguageMode => ’GermanToFrench’, Text => $ GET[’value’]); $result = $translation−>Translate($parameters); echo ”Result: {$result−>TranslateResult} <br>\n”; } catch (SoapFault $ex){ echo ”Error opening the connection {$ex−>faultsting}”; }

PHP Miscellaneous Web Services 53

slide-54
SLIDE 54

Parse a response

try{ $wsdl = ”http://www.toto.com/Horoscope.asmx?WSDL”; $horoscopeService = new SoapClient($wsdl, array(’trace’ => 1)); $parameters = array(); $result = $horoscopeService−>GetHoroscope(); echo ”Result: {$result} <br>\n”; foreach($result−>GetHoroscopeResult−>ZodiacSigns as $horo){ echo ”<b>{$horo−>ZodiacSign}</b>,”; echo ”{$horo−>DailyForecast}<br>\n”; } } catch (SoapFault $ex){ echo ”Error opening the connection {$ex−>faultsting}<br>\n”; }

PHP Miscellaneous Web Services 54

slide-55
SLIDE 55

Debug Soap Requests

◮ Debug Methods

getLastRequest(), getLastRequestHeaders(), getLastResponse(), getLastResponseHeaders()

◮ require to create the SoapClient with the trace option

$url = ”http://www.webservicex.com/TranslateService.asmx?WSDL”; $translation = new SoapClient($url, array(’trace’ => 1)); $parameters = array(LanguageMode => ’GermanToFrench’, Text => ’Das ist ein PHP Kurse’); $result = $translation−>Translate($parameters); echo htmlspecialchars($translation−> getLastRequest()).”<br>”; echo htmlspecialchars($translation−> getLastResponse());

PHP Miscellaneous Web Services 55

slide-56
SLIDE 56

Conclusion

PHP can do almost everything for the net

◮ Handle HTML / XML / WML / XHTML ◮ Acts like a real programming language (OO design, reg-exp,...) ◮ But handles web functionalities perfectly

  • Forms
  • Sessions
  • Cookies
  • Document generation (Images, PDF, Flash, . . . )

◮ Can be used for small to medium sized projects ◮ Code can not be used for a GUI

PHP Miscellaneous Conclusion 56