Preview only show first 10 pages with watermark. For full document please download

Sérgio Nunes

   EMBED


Share

Transcript

PHP Lab. 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 Serving Static Pages 2. Send request. Client 1. Set URL. 6. Render and present response. 3. Receive and process request. Web Server 5. Send response + file's content. 4. Read requested file from disk. Hard Disk Serving Dynamic Pages 3. Receive and process request. 2. Send request. Client 1. Set URL. Web Server 8. Send response + file's content. 9. Render and present response. 4. Read requested file from disk. Hard Disk 5. Request PHP module to process the file. 7. Return results. PHP Database APIs 6. Access other resources (e.g. database, APIs, etc). 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 After Execution Hello World! 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. 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. Strings • • • String concatenation is done with "." (dot). Supports char indexing using brackets. Common functions: explode, implode, strlen, strcmp, srtpos, substr, strtolower, strtoupper, trim … # 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. 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 name; } function sum($v1, $v2) { return $v1 + $v2; } } echo Test::sum(5, 6); $t = new Test(); $t->name = "LBAW"; echo $t->getName(); ?> // Static call. 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). Comments Control Structures 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 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 • 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. 1. First request. Client 2. Server response + cookie. n. Other requests + cookie. Server 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 ]]]]]) 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(). Database Access with 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 => => => => 'pgsql', 'someuser', 'apasswd', 'localhost', '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 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 error if (PEAR::isError($result)) { die($result->getMessage()); } // Get each row of data on each iteration until there are no more rows while (($row = $res->fetchRow())) { // Assuming MDB2's default fetchmode is MDB2_FETCHMODE_ORDERED echo $row[0] . "\n"; } ?> Fetch Associative Arrays query('SELECT id, name, email FROM users'); $row = $db->fetchRow($res, MDB_FETCHMODE_ASSOC); /* $row will contain: array ( 'id' => , 'name' => , 'email' => ) */ // Access the data with: $id = $row['id']; $name = $row['name']; $email = $row['email']; ?> // $id = $row[0]; // $name = $row[1]; // $email = $row[2]; Fetch by Number fetchInto($res, $fetchmode, $rowNum)) { break; } $id = $row['id']; // $id = $row[0]; [...] } ?> Insert & Update exec($sql); // Always check that result is not an error if (PEAR::isError($affected)) { die($affected->getMessage()); } ?> 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. • 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). Enables separation between presentation layer and business logic layer. Smarty PHP file html Browser php & html code PHP file php code vars Smarty Template file html code html Browser Smarty Example assign('s_userid', $s_userid); $smarty->assign('s_username', $s_username); $smarty->assign('s_usertype', $s_usertype); $smarty->display('index.tpl'); ?> index.php

Hello {$s_username}, glad to see you login with user {$s_userid}.

You have privileges of {$s_usertype}.

index.tpl Associative Arrays 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}
{$Contacts.email}
{* you can print arrays of arrays as well *} {$Contacts.phone.home}
{$Contacts.phone.cell}
index.tpl Common Features {include file="header.tpl" title="My Title"} includes {foreach item=user from=$users} {foreach key=type item=contact from=$user}

{$type}: {$contact}

{/foreach} {/foreach} foreach {if $type eq 2} {$name} {/if} 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 • / — 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 assign("avioes", $avioes); $smarty->display('listaravioes.tpl'); ?> listaravioes.php Example 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 pointers to external resources. References • PHP.net http://docs.php.net/ • PEAR MDB2 http://pear.php.net/package/MDB2/ • Smarty | PHP Template Engine http://www.smarty.net/