qddph240.php...Title qddph240.php.pdf Author S130254 Created Date 8/12/2014 2:57:18 PM
PHP - Faculdade de Engenharia da Universidade do...
Transcript of PHP - Faculdade de Engenharia da Universidade do...
PHPLab. de Bases de Dados e Aplicações Web
MIEIC, FEUP 2010/11
Sérgio Nunes
Summary
• Server-Side Development
• The PHP Language
• Smarty Template Engine
• Database Access with MDB2
Server-Side Development
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.
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.
Use Cases
• Process submitted form information.
• Manage user authentication.
• Interface with other services, e.g. databases, APIs, e-mail, etc.
• …
Server-Side Languages
• There are many server-side options.As many as programming languages.
• Most popular: PHP, Java, ASP, C#, Perl, Python, Ruby, etc.
PHP
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.
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
Features
• Free and open-source.
• Interpreted at run-time (not compiled).
• Weakly typed.
• Supports some OO concepts.
phpinfo
• Typical way to test a server installation.
• Lists built-in variables and settings.
• Lists which modules are enabled.
<?php phpinfo(); ?>
teste.php
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;?>
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".?>
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;?>
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.
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();?>
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');?>
Comments
<?php
# single-line comment
// single-line comment.
/* multi-line comment*/?>
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--; }?>
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.
Function Example<?php
$var = 3;
function sum( $val=10 ) { global $var; return $val + $var; }
echo sum(); // 13 echo sum(5); // 8?>
Includes
• The include() command inserts the entire contents of a given file into the PHP script.
• Useful for shared libraries.
• Fundamental for code modularity!
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.
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.
Session Control
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.
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.
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"];?>
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.
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();?>
Database Accesswith MDB2
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.
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();
?>
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";}?>
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]; ?>
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]; [...]}?>
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());?>
Smarty Template Engine
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).
Smarty
PHP file Browserhtml
php & html code
PHP file Smarty Template file
Browser
php code html code
vars html
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
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
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
Application Structure
User Pages
PHP file
include base files
get data with MDB2
present with Smarty
Action Pages
PHP file
include base files
get data with MDB2
redirect
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.
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
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
PHP.net
• Main PHP site — http://php.net
• Central documentation source.
• Supports user comments.
• Includes tutorials and also pointersto external resources.
References
• PHP.nethttp://docs.php.net/
• PEAR MDB2http://pear.php.net/package/MDB2/
• Smarty | PHP Template Enginehttp://www.smarty.net/