php - faculdade de engenharia da universidade do portossn/2010/lbaw/slides/lbaw-php.pdf · client...

52
PHP Lab. de Bases de Dados e Aplicações Web MIEIC, FEUP 2010/11 Sérgio Nunes

Upload: others

Post on 05-Jun-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

PHPLab. de Bases de Dados e Aplicações Web

MIEIC, FEUP 2010/11

Sérgio Nunes

Page 2: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Summary

• Server-Side Development

• The PHP Language

• Smarty Template Engine

• Database Access with MDB2

Page 3: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Server-Side Development

Page 4: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Client Web Server

Serving Static Pages

1. Set URL.

3. Receive and process request.2. Send request.

Hard Disk

4. Read requested file from disk.

5. Send response + file's content.

6. Render and present response.

Page 5: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Serving Dynamic Pages

Client Web Server

1. Set URL.

3. Receive and process request.2. Send request.

Hard Disk

4. Read requested file from disk.

8. Send response + file's content.

9. Render and present response.

5. Request PHP module to process the file.

PHPDatabase

APIs 6. Access other resources (e.g. database, APIs, etc).

7. Return results.

Page 6: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Use Cases

• Process submitted form information.

• Manage user authentication.

• Interface with other services, e.g. databases, APIs, e-mail, etc.

• …

Page 7: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Server-Side Languages

• There are many server-side options.As many as programming languages.

• Most popular: PHP, Java, ASP, C#, Perl, Python, Ruby, etc.

Page 8: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

PHP

Page 9: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Brief History

• Originally developed by Rasmus Lerdorf in 1994 to manage his home page.Initial acronym - "Personal Home Pages".

• Now "PHP: Hypertext Preprocessor".

• Adoption and popularity due to ease of coding and wide support in web servers.

Page 10: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

A PHP Script<!DOCTYPE html><html>

<head></head>

<body> <?php echo "Hello World!"; ?></body>

</html>

<!DOCTYPE html><html>

<head></head>

<body> Hello World!</body>

</html>

After Execution

PHP file HTML rendered

Page 11: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Features

• Free and open-source.

• Interpreted at run-time (not compiled).

• Weakly typed.

• Supports some OO concepts.

Page 12: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

phpinfo

• Typical way to test a server installation.

• Lists built-in variables and settings.

• Lists which modules are enabled.

<?php phpinfo(); ?>

teste.php

Page 13: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Variables

• Variables do not need to be declared.

• Names start with $ and are case sensitive.

• Loosely typed, i.e. variable type is dynamically defined.

<?php $var = 10; $var = "text";

$var2 = TRUE;?>

Page 14: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Strings

• String concatenation is done with "." (dot).

• Supports char indexing using brackets.

• Common functions: explode, implode, strlen, strcmp, srtpos, substr, strtolower, strtoupper, trim …

<?php $var = "LBAW"; print $var[1]; # outputs "B".?>

Page 15: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Arrays• PHP arrays are associative, i.e. they work like a hash

table with (key,value) pairs.

• Keys and values can be of any type.

<?php $array[0] = 5; $array["age"] = 22; $array["color"] = "blue";

print_r($array);

$array2 = array(5, "age"=>22, "color"=>"blue");

foreach ($array as $key => $value) echo $key . "=" . $value;?>

Page 16: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Classes

• In PHP is possible to define classes with the class keyword. Class attributes are defined with var, and class methods are defined with function.

• A class must be defined in a single file.

Page 17: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Class Example<?php class Test { var $name;

function getName() { return $this->name; }

function sum($v1, $v2) { return $v1 + $v2; } }

echo Test::sum(5, 6); // Static call.

$t = new Test(); $t->name = "LBAW"; echo $t->getName();?>

Page 18: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Output• The print() and echo() commands can be used to output

text from the PHP code.

• Before any output the function header() must be called to send the HTTP required headers. Also used to send HTTP error codes (e.g. 404 File Not Found).

<?php header();

print("Hello world!"); print("Hello world!\n");

print("String inside " are interpreted - $var"); print('Strings inside ' are not interpreted - $var');?>

Page 19: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Comments

<?php

# single-line comment

// single-line comment.

/* multi-line comment*/?>

Page 20: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Control Structures

<?php if ($var == 5) f1();

switch ($var) { case 10: f2(); break; default: f3(); }?>

<?php for ($x=1; $x<10; $x++) { print $x; }

while ($x > 1) { echo $x; $x--; }?>

Page 21: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Functions

• The function keyword is used to define functions in PHP.

• It is possible to define the function parameters and their default values.

• Functions may return values.

• Variables declared within the function are local. Use the global keyword to access global variables.

Page 22: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Function Example<?php

$var = 3;

function sum( $val=10 ) { global $var; return $val + $var; }

echo sum(); // 13 echo sum(5); // 8?>

Page 23: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Includes

• The include() command inserts the entire contents of a given file into the PHP script.

• Useful for shared libraries.

• Fundamental for code modularity!

Page 24: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

HTTP Parameters

• In HTTP, both POST and GET methods can handle parameters.

• With GET, parameters are included in the URL, e.g. http://google.com/search?q=pt

• With POST, parameters are included in the HTTP headers.

Page 25: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Handling Parameters

<?php

$_POST["name"]; $_GET["id"]; $_REQUEST["age"];

?>

• Request data is available in superglobal associative arrays:

• $_GET — contains variables passed through HTTP GET.

• $_POST — contains variables passed through HTTP POST.

• $_REQUEST — contains contents of $_GET and $_POST.

Page 26: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Session Control

Page 27: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Session Control

• HTTP is a stateless protocol.

• Each request is independent. No built-in way of handling user interactions (e.g. user authentication, shopping carts).

• Two standard approaches for servers to track users: cookies and sessions.

Page 28: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Cookies

• Client-side information storing.

• Cookies are pieces of data sent by web server that can be used by browsers in subsequent requests.

Client Server

1. First request.

n. Other requests + cookie.

2. Server response + cookie.

Page 29: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Cookies in PHP

• In PHP cookies are handled using the setcookie function.

• Cookie values are accessible in the superglobal variable $_COOKIE.

bool setcookie($name [, $value [, $expire [, $path [, $domain [, $secure ]]]]])

<?php $var = "anything";

setcookie("MyCookieName", $var);?>

<?php echo $_COOKIE["MyCookieName"];?>

Page 30: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Sessions

• Server-side information storing.

• A unique id (session id) is assigned to each visitor. This is information is stored in cookies or propagated via URLs.

• Servers store session information that is accessible using the session id as key.

Page 31: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Sessions in PHP

• Session handling is easy in PHP.

• Start a session using session_start(). After this, session variables can be created or accessed using the $_SESSION variable. A session is terminated using session_destroy().

<?php session_start();

echo session_id(); $_SESSION["prefs"] = $prefs; echo $_SESSION["prefs"];

session_destroy();?>

Page 32: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Database Accesswith MDB2

Page 33: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

PEAR MDB2

• PEAR is a framework and distribution system for reusable PHP components.

• PEAR MBD2 is a PHP database abstraction library. It provides a common API for RDBMS accesses.

• Other options: eZ Database, Zend ActiveRecord, Doctrine, etc.

Page 34: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Database Connection<?phprequire_once 'MDB2.php';

// Data Source Name: This is the universal connection string$dsn = array( 'phptype' => 'pgsql', 'username' => 'someuser', 'password' => 'apasswd', 'hostspec' => 'localhost', 'database' => 'thedb',);

$options = array( 'debug' => 2, 'portability' => MDB2_PORTABILITY_ALL,);

// uses MDB2::factory() to create the instance and also attempts to connect to the host$mdb2 =& MDB2::connect($dsn, $options);if (PEAR::isError($mdb2)) { die($mdb2->getMessage()); }

[...]// close connection$mdb2->disconnect();

?>

Page 35: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Query Execution<?php[...]// Create a valid MDB2 object named $mdb2 at the beginning of your programrequire_once 'MDB2.php';

$mdb2 =& MDB2::connect('pgsql://usr:pw@localhost/dbnam');if (PEAR::isError($mdb2)) { die($mdb2->getMessage());}

// Proceed with a query...$sql = 'SELECT * FROM clients where email = ? and address = ?';$data= array($email, $address));

$result =& $mdb2->query($sql, $data);

// Always check that result is not an errorif (PEAR::isError($result)) { die($result->getMessage());}// Get each row of data on each iteration until there are no more rowswhile (($row = $res->fetchRow())) { // Assuming MDB2's default fetchmode is MDB2_FETCHMODE_ORDERED echo $row[0] . "\n";}?>

Page 36: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Fetch Associative Arrays<?php$res = $db->query('SELECT id, name, email FROM users');$row = $db->fetchRow($res, MDB_FETCHMODE_ASSOC);

/*$row will contain:array ( 'id' => <column "id" data>, 'name' => <column "name" data>, 'email' => <column "email" data>)*/

// Access the data with:$id = $row['id']; // $id = $row[0]; $name = $row['name']; // $name = $row[1]; $email = $row['email']; // $email = $row[2]; ?>

Page 37: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Fetch by Number<?php[...]// the row to start fetching$from = 50;

// how many results per page$resPage = 10;

// the last row to fetch for this page$to = $from + $resPage;

foreach (range($from, $to) as $rowNum) { if (!$row = $db->fetchInto($res, $fetchmode, $rowNum)) { break; } $id = $row['id']; // $id = $row[0]; [...]}?>

Page 38: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Insert & Update<?php// Once you have a valid MDB2 object named $mdb2...$sql = "INSERT INTO clients (id, name, address) VALUES ($id, $name, $address)";

$affected =& $mdb2->exec($sql);

// Always check that result is not an errorif (PEAR::isError($affected)) { die($affected->getMessage());}?>

<?php// Once you have a valid MDB2 object named $mdb2...

$sql = 'UPDATE clients SET name = ?, address = ? WHERE id = ?';$types = array('text', 'text','integer');

$sth =& $mdb2->prepare($sql, $types, MDB2_PREPARE_MANIP);

$res =& $sth->execute(array($name, $address, $id));

if (PEAR::isError($res)) die($res->getDebugInfo());?>

Page 39: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Smarty Template Engine

Page 40: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Smarty

• Smarty is a template engine for PHP.

• Enables separation between presentation layer and business logic layer.

• PHP was originally designed to be included in HTML files. Can easily lead to code repetition and lower readability. Harder to maintain.

• Different type of work can easily be separated (e.g. design vs. programming).

Page 41: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Smarty

PHP file Browserhtml

php & html code

PHP file Smarty Template file

Browser

php code html code

vars html

Page 42: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Smarty Example<?php include_once('Smarty.class.php');

$smarty = new Smarty;

[...]

$smarty->assign('s_userid', $s_userid); $smarty->assign('s_username', $s_username); $smarty->assign('s_usertype', $s_usertype);

$smarty->display('index.tpl');?>

<p>Hello {$s_username}, glad to see you login with user {$s_userid}.</p><p>You have privileges of {$s_usertype}.</p>

index.php

index.tpl

Page 43: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Associative Arrays<?php $smarty->assign('Contacts', array('fax' => '555-222-9876', 'email' => '[email protected]', 'phone' => array('home' => '555-444-3333', 'cell' => '555-111-1234') ) ); $smarty->display('index.tpl');?>

index.php

{$Contacts.fax}<br />{$Contacts.email}<br />{* you can print arrays of arrays as well *}{$Contacts.phone.home}<br />{$Contacts.phone.cell}<br />

index.tpl

Page 44: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Common Features

{if $type eq 2} {$name}{/if}

{foreach item=user from=$users} {foreach key=type item=contact from=$user} <p>{$type}: {$contact}</p> {/foreach}{/foreach}

{include file="header.tpl" title="My Title"}

includes

foreach

ifs

Page 45: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Application Structure

Page 46: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

User Pages

PHP file

include base files

get data with MDB2

present with Smarty

Page 47: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Action Pages

PHP file

include base files

get data with MDB2

redirect

Page 48: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Application Files

• /<webapp> — PHP files.

• /lib — Required libraries (e.g. Smarty, MBD2, etc.).

• /includes — DB, Smarty and session setup.

• /database — DB access files. A file per class per entity.

• /templates — Smarty template files.

• /templates_c — Smarty cache.

Page 49: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Example

<? require_once('includes/base.php'); require_once('database/avioesmodelos.php');

$nome = $_GET["nome"]; $modelo = $_GET["modelo"]; $avioes = AvioesModelos::getByNomeModelo($nome, $modelo);

$smarty->assign("avioes", $avioes); $smarty->display('listaravioes.tpl');?>

listaravioes.php

Page 50: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

Example<? require_once('includes/base.php'); require_once('database/avioes.php'); if ($_POST['nome'] == "") $_SESSION['s_errors']['nome'] = 'O nome não pode ser vazio';

if ($_SESSION['s_errors']) { $_SESSION["s_values"] = $_POST; header("Location: " . $_SERVER['HTTP_REFERER']); die; }

if ($s_tipo != 'admin') {header("Location: index.php");die;}

$nome = $_POST['nome']; $codmodelo = $_POST['codmodelo'];

$errors = Avioes::insert($nome, $codmodelo);

if ($errors) { $_SESSION["s_errors"] = $errors; $_SESSION["s_values"] = $_POST; header("Location: " . $_SERVER['HTTP_REFERER']); } else { $_SESSION["s_messages"][] = "Avião Criado com Sucesso"; header("Location: veraviao.php?codaviao=" . Avioes::getLastInsertedId()); }?>

accaonovoaviao.php

Page 51: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

PHP.net

• Main PHP site — http://php.net

• Central documentation source.

• Supports user comments.

• Includes tutorials and also pointersto external resources.

Page 52: PHP - Faculdade de Engenharia da Universidade do Portossn/2010/lbaw/slides/lbaw-php.pdf · Client Web Server Serving Static Pages 1. Set URL. 3. Receive and process request. 2. Send

References

• PHP.nethttp://docs.php.net/

• PEAR MDB2http://pear.php.net/package/MDB2/

• Smarty | PHP Template Enginehttp://www.smarty.net/