Php language for cloud applications Web-based applications: main elements HTTP PROTOCOL CLIENT SIDE SERVER SIDE HTTP request • An HTTP request consists of: a request method (verb), resource URL, header fields (metadata), body (data) • HTTP 1.1 defines 9 request methods, among which: • GET: Retrieves the resource identified by the request URL • HEAD: Returns the headers identified by the request URL • POST: Sends data of unlimited length to the Web server • • PUT: Stores a resource under the request URL • DELETE: Removes the resource identified by the request URL • HTTP 1.0 includes only the GET, HEAD, and POST methods. HTTP response • An HTTP response contains a result code, header fields, and a body. • • • • • • • • Some commonly used status codes include: 100: Continue 200: OK 401: the request requires HTTP authentication 404: the requested resource is not available 500: an error occurred inside the HTTP server that prevented it from fulfilling the request 503: the HTTP server is temporarily overloaded and unable to handle the request • For detailed information on this protocol, see the Internet RFCs: HTTP/1.0 (RFC 1945), HTTP/1.1 (RFC 2616). (http://www.rfc-editor.org/rfc.html) Example Example HTTP is ‘stateless’ • Although HTTP uses the TCP protocol, it has no notion of enduser • For example, filling in data through multi-page forms requires the server to keep track of which client is requesting the page. First Name: Second Name: …. Location: ---: …. First step Second step Static web pages HTTP PROTOCOL Content •Content is pre-determined •Web pages are static Sequence diagram BROWSER HTTPD Get URL Get html file FILE SYSTEM Send html file Render html Dynamic web pages • Content of a page is not static • Page content is changes based on: – User input, form completion,etc. – Database interaction – External data sources (db, service provider) • Server side techniques • Client side techniques Technique overview • Client Side – Script • Source code passed from the server and executed by the browser – Compiled code • Applet (no longer used…) • Server side – CGI (Common Gateway Interface) • An http request triggers the execution of an independent program • Data passed via standard input or environment variables – Script • code executed inside the server process • Interleaved with html code (php) • Confined into a different page (code behind, e.g., ASP.NET) Principle of server-side CGI programs BROWSER HTTPD CGI-process Get URL Execute program Send html file Build html on-the-fly Read/Write data FILE SYSTEM Render html Client sends the request along with data (e.g., from a form) The server lunches a process and transmits data input to the program The program writes a html page The web server sends the page back to the client Accessing a data source BROWSER HTTPD CGI-process Get URL Execute program Send html file Render html Build html on-the-fly Query DB System level view FILE SYSTEM CGI HTTPD CGI PROCESS Bottlenecks round-trip time FILE SYSTEM CGI HTTPD CGI PROCESS One process per request Bottlenecks round-trip time FILE SYSTEM HTTPD + functions.. Integrate the functionality as an additional module of the server process… (script) Bottlenecks Make the browser ‘smart’ (execute code or script) FILE SYSTEM HTTPD + functions.. Integrate the functionality as an additional module of the server process… (script) Principle of server side script WEB Client WEB SERVER html document SCRIPT HTTP SCRIPT Script engine • • • • • • • Pages are generated by a program A html document at the server side includes the code to be executed (script) The code is delimited via special escape characters The web server extracts the script part from the document A script engine runs the code Web server replaces the script with the output of the execution Client sees pure html (no way to access the code) Principle of client-side script Web Client Script engine • • • • • • html document at the client side contains the code to be executed The code is delimited via special escape characters The client extracts the script part from the document Executes the code It can perform computation, remote communication, change the rendering of a document It can access local events (mouse events,..) Client-side vs server-side • Client-side – Minimal processing on the server. Server sends web page with embedded script. Client browser executes the script – Client browser may not fully support, or script execution turned off – Security issue (user can see the script) – Cross-browser compatibility • Library may help (e.g., jQuery) Client-side vs server-side • Server-side – Easier to create large-scale site. Create a small set of dynamic pages – Poor coding programmer may open resources to attack through security flaws Introduction to PHP • Scripting language • Server side execution – Code is scattered inside a html document – The web server executes the code and produces a simple html page. PHP code embedding <HTML> <HEAD>Sample PHP Script</HEAD> <BODY> The following prints "Hello, World": <?php print "Hello, World"; ?> </BODY> </HTML> Every time the PHP interpreter reaches a PHP open tag <?php,it runs the enclosed code up to the delimiting ?>marker. Can be changed, see short_open_tags INI option; PHP code embedding <HTML> <HEAD>Sample PHP Script</HEAD> <BODY> The following prints "Hello, World": <?php print "Hello, World" ?> </BODY> </HTML> <HTML> <HEAD>Sample PHP Script</HEAD> <BODY> The following prints "Hello, World": Hello, World </BODY> </HTML> Every time the PHP interpreter reaches a PHP open tag <?php,it runs the enclosed code up to the delimiting ?>marker. Variables • A variable always starts with the dollar sign $ – $a – $A – $1 (not allowed) • Identifiers are case sensitive (not when referring to function) • Variable and function can have the same name! Types • Basic types like in other programming languages – Boolean, Integer, Floating Point, Object, • Main difference concerns: – string (regular expression,…) • single quoted (variables are not replaced with their values) • double quoted (variables are replaced with their values) • … – array (associative arrays) • Other types: – null • No type associated yet – resource • Generic type, e.g. the result of a query Types • PHP uses a Weakly Typed System • variables’ type is not declared • PHP automatically converts the variable to the correct data type, depending on how they are set • $integer=10 • $float = 10.0 • $string = “10” Some example $a = “fine” // $a is a string $a = 10; // $a is an integer $b = 6.3; $c = $a + $b; /* $c is a float */ $d = (int)$c; // type casting ($d integer) gettype($d); settype($d, double); // $d is now double $e = settype($d, double); // $d is now double print(gettype($e)); // print boolean if (is_int($d)) // is_type to type check Variable variables <?php $name = "John"; $$name = "Registered user"; print $John; //display “Registered user” ?> John $name Registered user $$name (=$John) Managing variables • isset () – determines whether a certain variable has already been declared by PHP. • unset() – “undeclares” a previously set variable, and frees any memory that was used by it if no other variable references its value. • empty () – empty() may be used to check if a variable has not been declared or its value is false. Variable’s scope • Names inside a function has local scope • Script level names can be accessed through the special builtin array $GLOBALS $m main script function Af $a is only visible in the function Af’s scope $m can be seen via $GLOBALS[m] $a function Bf $b $b is only visible in the function Bf’s scope $a is not visible $m can be seen via $GLOBALS[m] Predefined System "Superglobals" • Provide access to key runtime data elements. • Set by and managed through web server runtime environment and available to the script. • Superglobals are key to form processing, cookies, and other techniques. Some Superglobals • $_GET[ ]. An array that includes all the GET variables that PHP received from the client browser. • $_POST[ ]. An array that includes all the POST variables that PHP received from the client browser. • $_COOKIE[ ]. An array that includes all the cookies that PHP received from the client browser. • $_SERVER[ ]. An array with the values of the web-server variables. Output: echo statement • Placing a variable outside quotes outputs the variable’s value (line 2) • Single quote ' sends literal string output (line 3), no variable value substitution • Double quote “ sends variable value (line 4) 1 2 3 4 <?php $a=6; echo $a; echo 'The var name is $a'; echo "The var contains $a"; ?> Note: no declaration (line 1) Output: echo statement • To achieve newlines in browser, use appropriate tagging • Use \ to escape (negate) the effect of the following character <?php $a=6; echo $a; echo 'The var name is $a'. '<br>'; echo "The var contains $a"; ?> 1.3.php <?php echo "She said, \"How are you?\""; echo "<a href=\"page.htm\">link</a>"; ?> 1.4.php Constant • Unchangeable values. In all caps by convention. No $. <?php define('MYCONST',100); define('NAME',"My Name"); ?> • • • • To output, must list constant name outside of ' and ". echo "Hello, ".NAME; Predefined system constants also exist. To see a complete list: print_r(get_defined_constants()) Output: print_r() • print_r() can be used to "dump" variable output, typically for debugging of complex structures. <?php print_r($_SERVER); ?> Example <?php $user = (isset($_GET[‘user’]) ? $_GET[‘user’]:”” ); … ?> Comments • Multi-line comments /* This is a multi-line comment */ • Single line comments // This single line is commented # So is this single line – PHP comments are distinct from HTML comments in that PHP comments are not sent to the client browser. Operators • +, -, *, /, %, ++, -- same as other languages • Combining above with = for assignment can be done: • +=, -=, *=, /=, %=, .= • Two Comparison operators • == (performs type conversion) • === (no type conversion) • ‘1’==1 true • ‘1’===1 false Input data: Form • A form is an area that can contain form elements • Form elements are elements that allow the user to enter information • A form wraps input tags – – – – … text fields Radio buttons Checkboxes Submit • A form has a url to which sending the input data (see later) Input tag (HTML4) Examples First name: <input type="text" name="firstname"> <br> Last name: <input type="text" name="lastname"> <br><br> <input type="radio" name="sex" value="male"> Male <br> <input type="radio" name="sex" value="female"> Female <br><br> I have a bike: <input type="checkbox" name="vehicle" value="Bike"> <br> I have a car: <input type="checkbox" name="vehicle" value="Car"> <br> <input type="submit" name="Submit" value="go"> <br> Some nice feature from HTML5 type=“email” type=“url” type=“number” type=“range” Rendering on mobile phones http://diveintohtml5.info LAB • LAB1: Write a program that echo back the number entered • LAB2: Write a program that writes back the sign of the number (how to check that the input was a number?) • LAB3: Write a program that displays the previous form and, after submission, it lists all the input data LAB (php + ajax) • Read data from a text input in an input form • Ajax call to a PHP function for echoing the character back • What we need – Keyboard event listener (JS function) – AJAX request that passes the text to the script – PHP script that echo the text back to the client In this form there is no submit button JS function called when key is released <form name="testForm"> Input text: < input type="text" onkeyup="doWork();" name="inputText" id="inputText" /> Output text: <input type="text" name="outputText" id="outputText" /> </form> function do_it() { document.testForm.outputText.value=request.responseText; }; .. var request = false; .. function doWork(){ var URL = "http://localhost/test.php?char="; request = new XMLHttpRequest(); request.open("GET", URL+document.getElementById('inputText').value, true); request.send(null); request.onreadystatechange = do_it; } open method used for preparing the request send sends the request php script do_it is the event listener for the reply <?php echo $_GET['char']; ?> Example • TrackMe, a simple application that tracks positions of a mobile device: – track.html: js that sends gps position – trackMe.php: write the coordinate to a file – Monitor.php: periodically reads the file and shows the positions. Example 1 track.html Browser .js monitor.php 2: HTTP GET trackMe.php track.html (1/2) <html> <head> <title> Track Me!</title> </head> <body> <input type="text" id = "text" value="" size=100/> <script type="text/javascript"> function done() { document.getElementById('text').value="Tracked.."; } track.html (2/2) navigator.geolocation.getCurrentPosition(showPosition); function showPosition(position) { var lat=position.coords.latitude; var lon=position.coords.longitude; var URL = "http://psd.altervista.org/GEO/trackMe.php?lat="+lat+"&lon="+lon; request = new XMLHttpRequest(); request.open("GET", URL, true); request.send(null); request.onreadystatechange = done; document.getElementById('text').value="Long: "+lon+" Lat: "+lat; } </script> </body> </html> TrackMe trackMe.php <?php $lat='?'; $lon='?'; if (isset($_GET['lat'])) $lat=$_GET['lat']; if (isset($_GET['lon'])) $lon=$_GET['lon']; $entry=date(c).' '.$lat.' '.$lon."\n"; file_put_contents ('position.txt', $entry, FILE_APPEND); ?> Monitor.php <head> <meta http-equiv="refresh" content="5" > </head> <?php $str=file_get_contents('position.txt'); echo nl2br($str); ?> Form submission <form name="input" action="process.php" method="get"> browser server get form.html reply get process.php reply http://localhost/process.php?firstname=A&lastname=B&sex=male&vehicle=Bike&Submit=go Processing data form html FORM Collects information Send data PHP Script (form processing) html output of results Send .html back DB access Creating a form • Key elements: – Input fields must be contained inside a form tag. – All input fields must have a name. – Names cannot have spaces in them. Fields should be named well for clear identification. • Form action should be URL to PHP processing script. • Appropriate form transmission method selected: – GET or POST. GET vs POST • Name/value pairs appended in clear text to the URL of the receiving page/script. • Each name/value pair separated by '&'. Value data automatically URL encoded. • Names are taken from the form field names. • GET URLs can be saved, bookmarked, etc. and used to recall the script with the same data. • GET strings provide 'transparency' that may/may not be desired. • Data available into the $_GET superglobal GET vs POST • Data is encoded in the page request body sent by the browser, but not shown in the URL. Unseen to user. • Since data not part of URL, bookmarking and reusing URL to recall the script with the same data is not possible. • Large POST packets not a problem. • Data available into the $_POST superglobal An example <html> <head><title>Register</title></head> <body> <h1>Registration</h1> <form method="get" action="register.php"> <table> <tr> <td>E-mail address:</td> <td> <input type='text' name='email'/></td> </tr> <tr> <td>First name:</td> <td><input type='text' name='first_name'/></td> </tr> <tr> <td>Last name:</td> <td><input type='text' name='last_name'/></td></tr> <tr> <td>Password:</td> <td> <input type='password' name='password'/> </td></tr> <tr> <td colspan='2'> <input type='submit' name='register' value='Register'/> </td> </tr> </table> </form> </body> </html> An example method <html> Processing <head><title>Register</title></head> script <body> <h1>Registration</h1> <form method="get" action="register.php"> <table> <tr> <td>E-mail address:</td> <td> <input type='text' name='email'/></td> </tr> <tr> <td>First name:</td> <td><input type='text' name='first_name'/></td> </tr> <tr> <td>Last name:</td> <td><input type='text' name='last_name'/></td></tr> <tr> <td>Password:</td> <td> <input type='password' name='password'/> </td></tr> <tr> <td colspan='2'> <input type='submit' name='register' value='Register'/> </td> </tr> </table> </form> </body> </html> Input tags key value http://localhost/register.php?email=PSD&first_name=Piattaforme&last_name=SW&password=Pippo&register=Register Input validation • Never assume a form: – is filled out completely – Contains the type of information requested – Has been submitted by a benign user – Only contains the fields and values or value ranges expected • Check all form data to verify that it is complete and valid … • … and secure! Input validation • • • • Required Fields are filled Type is correct Length is ‘reasonable’ Structure adhere to a scheme – Regular expression – Check consistency • No malicious data – SQL injection – Cross-site scripting Helpful form validation functions • Functions exist for testing data types: • is_numeric($x), etc.,. • isset($var) – does $var exist? • empty($var) – returns false unless $var contains an empty string, 0, "0", NULL, or FALSE. Example • How to check if first name is correct? $fn= $_GET[‘first_name’]; if (empty($fn) || isnumeric($fn) || strlen ($fn)<3 || strlen ($fn)>10) die(“Not valid data…”); Other tricky checks • Radio buttons and check box may not be set $ if !(isset($_GET[‘gender'])) && ($_GET[‘gender’]==‘Male’ || $_GET[‘gender’]==‘Famale’)): die(“…”) Other tricky checks • Suppose you are designing a guest book, or a survey where people tell their impression '<script language='Javascript'>alert('ALLARM!');</script>' User authentication: naïve approach <h1>Login</h1> <form method=“get" action="login.php"> <table> <tr> <td>User name:</td> <td> <input type='text' name=‘user'/></td> </tr> <tr> <td>Password:</td> <td> <input type='password' name=‘pwd'/></td> </tr> .. </table> </form> http://example.com/login?user=pippo&pwd=pippo <?php $query=“SELECT login_id FROM users WHERE users=‘$user’ AND pwd=‘$pwd’ ”; $ans = mysql_query($query) .. ?> SQL injection • Exploiting an application that takes data from user input and uses it to form an SQL query without proper "sanitation". • Let consider this… # starts a comment http://example.com/login?user=admin’;# $query=“SELECT login_id FROM users WHERE users=‘$user’ AND pwd=‘$pwd’ ”; $query=“SELECT login_id FROM users WHERE users=‘admin’; # AND pwd=‘’ ”; Conditional control structures if (expr) statement elseif (expr) statement elseif (expr) statement ... else statement { statement1; statement 2; } if ($num<0) print '<h1>$num is negative</h1>'; elseif ($num==0) print '<h1>$num is zero</h1>'; else print '<h1>$num is positive</h1>'; if (expr): statement list elseif (expr) : statement list ... else : statement list endif; <?php if ($num < 0): ?> <h1>$num is negative</h1> <?php elseif($num == 0): ?> <h1>$num is zero</h1> <?php else: ?> <h1>$num is positive</h1> <?php endif; ?> Traditional loop control structures while (expr) statement while (expr) : statement list endwhile; for (expr, expr, …; expr, expr, …; expr, expr, …) statement for ($i = 0; $i <= count($array); $i++) { } $count = count($array); for ($i = 0; $i <= $count; $i++) { } do statement while (expr); Html table <table border="1"> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> </tr> </table> td = table data tr = table row Exercise • Write a simple php program that displays the Pitagora’s table. The size of the table is a parameter passed through a form.. Array array([key =>] value, [key =>] value, ...) • The key is optional, and when it’s not specified, the key is automatically assigned one more than the largest previous integer key (starting with 0). • There are three different kind of arrays: – Numeric array - An array with a numeric ID key – Associative array - An array where each ID key is associated with a value – Multidimensional array - An array containing one or more arrays Examples 1. 2. 3. 4. 5. 6. array(1, 2, 3) array(0 => 1, 1 => 2, 2 => 3) array ("name" => "John", "age" => 28) array(1 => "ONE", "TWO", "THREE") array(1 => "ONE", 2 =>"TWO", 3 => "THREE") array (array ("name" => "John", "age" => 28), array ("name" => "Barbara", "age" => 67)) 1 and 2 are same, 4 and 5 are same, 6 is a nested array Examples $arr1 = array(1, 2, 3); $arr2[0] = 1; $arr2[1] = 2; $arr2[2] = 3; print_r($arr1) $arr1 = array("name" => "John", "age" =>28); $arr2["name"] = "John"; $arr2["age"] = 28; if ($arr1 == $arr2) { print '$arr1 and $arr2 are the same'; } Array ( [0] => 1 [1] => 2 [2] => 3 ) $arr1 and $arr2 are the same Traversing foreach($array as [$key =>] [&] $value) • $key contains the currently iterated value’s key • & if present allows to modify the array • $value contains the value $players = array ("John", "Barbara", "Bill", "Nancy"); print "The players are:<br>"; foreach ($players as $key => $value) { print "#$key = $value<br>"; } The players are: #0 = John #1 = Barbara #2 = Bill #3 = Nancy More on iterations • The data in the array is not contiguous, so incrementing a counter for the next access will not work correctly unless the array index values are used in the "traditional" way • We can also use other iterators such as next and each to access the array elements – next gives us the next value with each call • It moves to the next item, then returns it, so we must get the first item with a separate call (ex: use current()) $curr = current($a1); while ($curr): echo "\$curr is $curr <BR />\n"; $curr = next($a1); endwhile; More on iterations: each • each returns an array of two items: – A key field for the current key – A value field for the current value – It returns the next (key,value) pair, then moves, so the first item is no longer a special case while ($curr = each($a1)): $k = $curr["key"]; $v = $curr["value"]; echo "key is $k and value is $v <BR />\n"; endwhile; – This function may be preferable to next() if it is possible that FALSE or an empty string or 0 could be in the array • The loop on the previous slide will stop for any of those values Exercise • Format the output of the players as a html table Exercise <?php $players = array ("John", "Barbara", "Bill", "Nancy"); print 'The players are<br><table border="1">'; foreach ($players as $key => $value) { print '<tr><td>'."$key".'</td><td>'."$value".'</td></tr>'; } print '</table>' ?> concat double quoted to replace $key with its value Array related functions … Example LAB (tris) Tris as a Service Goal • Design a simple application for the tic-tac-toe game that allows to play – One user against the computer – Two players • Use a ‘Web API’ based approach for gluing the game (decide and control who can move, etc.) 1 Player: Simplest solution • Player maintains a table representing the state of the game • It performs an AJAX call for sending the state of the table (JSON). The call returns back the next move Architecture Filetto.php AJAX call Filetto.php 0 TRIS.php CLIENT SERVER Cells labeled fron 0 to 8 8 2 players • More complex: login(?), synchronization, store the state TRIS SERVICE 1. Initialize 1. Wait for my turn 2. Update the local state 3. Make the move Player 1 Player 2 2 players • Possible solution: A service with 4 operations for initialization, get the next turn, return the last move, update the last move TRIS SERVICE 1. Wait for my turn 2. Update the local state 3. Make the move Player 1 write read 1. Initialize turn.txt move.txt getTurn Player 2 2 players: client side moveEnabled= false; //disable onClick event handler T = [] // initialize the table getTurn; //periodically poll the service if not your turn then getTurn else moveEnabled=true read; //service call update_local_state; //local computation check_win(); //local computation make_the_move; //respond to the onClick event check_win(); moveEnabled=false write; //service call 2 players: service side init: turn=0; //write into a file move=-1; read: return move; write (mv,player): if (player==turn): move=mv; turn=(turn+1)%2 *: return ‘error’; Functions • Any valid PHP code may appear inside a userdefined function, even other function… • Functions need not be defined before they are referenced • Call-by-reference, call-by-value, default value, variable-length argument, lambda-style function Parameter passing function function_name (arg1, arg2, arg3, …) { statement list } parameter by-value function square(&$n) { $n = $n*$n; } … by-reference function square($n) { $n = $n*$n; } Default value function makeAcoffee ($type=“espresso”) { return “Making a cup of $type”; } echo makeAcoffee(); echo MakeAcoffee(“French”) • The default value must be a constant • Default arguments should be on the right side of any non-default argument Variable-length argument list function foo() { $numargs = func_num_args(); echo "Number of arguments: $numargs\n"; } foo(1, 2, 3); Variable function • If a variable name has parentheses appended to it, PHP looks for a function with that name and executes it function foo() {echo “in foo()<br>”;} $func = ‘foo’; $func(); #call foo() Static variables function do_something() { static $first_time = true; if ($first_time) { // Execute this code only the first time the function is called ... $first_time=false; } // Execute the function's main logic every time the function is called ... } Array_map • Applies a callback function to the elements of the given arrays <?php function Double($a){return 2*$a;}; $in = range(1,5); $out = array_map("Double",$in); print_r($out); ?> • • • • Other interesting functions (see manual): array_walk array_reduce … Code inclusion control structures include file_name; include_once file_name; include only once require file_name; require: stop if not available require_once file_name; include URL; if allow_url_fopen is set include "http://www.example.org/example.php"; include $_SERVER["DOCUMENT_ROOT"] . "/myscript.php"; Persistency • Cookie, Session much more with HTML5! – Per browser data storage, no cross-browser data exchange • File, DB – Site level persistence storage Cookie • A cookie is sent in the http header and it is stored at the client side (browser) until its lifetime • A browser can disable cookie storage • A cookie is a name=value pair (text up to 4096 bytes) • A cookie is bounded to the domain that generated it • Permanent cookie (with lifetime) or session cookie Cookie • A cookie is sent in the http header and it is stored at the client side (browser) until its lifetime • A browser can disable cookie storage • A cookie is a name=value pair (text up to 4096 bytes) • A cookie is bounded to the domain that generated it • Permanent cookie (with lifetime) or session cookie http header sent from the server to the client Set-Cookie: TRY=THIS IS A COOKIE; expires=Thu,19-May-2012 00:00:00 GMT; path = /; domain=.dis.uniroma1.it Header sent from the client to the server Cookie: TRY=THIS IS A COOKIE Inspecting http header • Browsers can install plug-in to inspect http headers • For example, liveHTTPHeader for firefox Cookie in PHP Output must be buffered <?php ob_start(); ?> <html> <head><title>Cookie example</title></head> <body> <?php setcookie(MyCookie,'ciao') ?> </body> </html> set a cookie (see documentation) Cookie in PHP • Cookie can be accesed via superglobal variable, $_COOKIE <?php print_r($_COOKIE); ?> Example • Implement a simple counter using Cookie Solution <?php ob_start(); ?> <HTML> <HEAD> <TITLE>COUNTER</TITLE> </HEAD> <BODY> <form method=“post" action="counter.php"> <table> <tr><td colspan='2'> <input type='submit' value='Inc' name='inc'/> </td></tr> <tr><td colspan='2'> <input type='submit' value='Dec'name='dec'/></td></tr> </table> </form> Solution <?php if (!isset($_COOKIE[C])): print "Counter=0"; setcookie(C,0); else: $Counter = $_COOKIE[C]; if (isset($_POST[inc])): $Counter++; endif; if (isset($_POST[dec])): $Counter--; endif; print "Counter=$Counter"; setcookie(C,$Counter); endif; ?> </BODY> </HTML> Tic Tac Toe with coockie P=P1, enters for the first time Display Form Player enters P=P1, returns, P2 not entered Set Cookie P1 display “Wait” display “Wait” Player arrives Index SYNC P=P1, returns, P2 entered redirect Display Form P=P2 P = Player P1 = First Player that arrives P2 = Second Player Set Cookie P2 redirect Tic Tac Toe Display new view move PLAY Update the view Check winner Session • A PHP session allows for storing information locally at the server on a per session basis – Session data path is specified in the session.save_path of php.ini – Data session can be stored in a database • PHP generates a session ID and sends it out as a cookie with name PHPSESSIONID • The client sends the session ID each time it interacts again with the same site Example <?php session_start(); ?> create the id and an empty _SESSION array, stored at the server side cookie cookie’s content Access to a private area • Session can be used to protect a page • When trying to access a page, check if authorization is set… • If not, redirect to a login page and then back to the page… • ..otherwise just continue.. <?php ob_start(); session_start(); ?> auth not set get this url.. redirect to login Example <?php if (!(isset($_SESSION['auth'])&&($_SESSION['auth']=='ok’))) { $url = $_SERVER['PHP_SELF']; header("location: login.php?url=$url"); } ?> Included in example.php set auth get original url redirect back <?php //check login… $_SESSION['auth']='ok'; $url=$_GET['url']; header(“location: $url"); ?> login.php http://localhost/example.php http://localhost/login?url=example.php http://localhost/example.php Example: shopping cart • • • • Simple example User can login… User can select/deselect items… …then check out… LAB login failure cookie ‘uid’ not set login.php success / set cookie ‘uid’ index.php done want to register unset cookie ‘uid’ click on logout passwd DB register.php logout.php SQLite / SQLite3 • • • • Light and fast, shipped with php5 No dedicated servers are required Procedural and object oriented APIs Cons: Lock mechanism is not very efficient Open/create a db resource sqlite_open ( string $filename [, int $mode [, string &$error_message ]] ) Opens a SQLite database or creates the database if it does not exist. <?php if ($db = sqlite_open("SIMPLE.DB",0666,&$error)) print("DB OPENED...."."\n"); else die($error); ?> SIMPLE.DB <?php $db = new SQLiteDatabase("SIMPLE.DB", &$error); if ($db) echo “DB OPENED...."; else die($error); ?> Create a table bool queryExec ( string $query [, string &$error_msg ] ) Executes a result-less query against a given database Sql statment Two types: integer and text (similar to varchar) PRODUCTS db id description quantity $create_query = " CREATE TABLE PRODUCTS ( id integer primary key, description, quantity integer ) "; $db->queryExec($create_query); Insert a row $query = "INSERT INTO PRODUCTS (id,description,quantity) VALUES (1,'DVD',1)"; $db->queryExec($query); id Description quantity 1 DVD 1 PRODUCTS db Update/delete $db->queryexec('DELETE FROM PRODUCTS WHERE id=2'); $db->queryexec('UPDATE PRODUCTS SET id=19 WHERE id=4'); Fetch results SQLiteResult fetch, fetch all, query seek rewind, current… unbufferedquery SQLiteUnbuffered forward only, much faster Fetch results $q = "SELECT * FROM PRODUCTS;"; $qr = $db->query($q); //Executes a query against a given database and returns a result handle $r = $qr->fetchAll();//Fetches all rows from a result set as an array of arrays foreach ($r as $entry) { echo $entry['id'].' '.$entry['description'].' '.$entry['quantity'].'<br>'; } 1 DVD 1 LAB /Project (shopping cart 2) • PRODUCT table – View content – Insert items – Delete items • Password DB – User registration – User authentication Login Form • http://www.html-form-guide.com/phpform/php-registration-form.html OO Model • • • • An OO program is a collection of objects Every object is an instance of a class An object has properties An object has a set of methods Constructor • Unified constructor name • __construct() class MyClass { function __construct() { echo "Inside constructor"; } } Destructor • __destruct() • Called when an object is destroyed (no more reference) class MyClass { function __destruct() { print "An object of type MyClass is being destroyed\n"; } } $obj = new MyClass(); $obj = NULL; An object of type MyClass is being destroyed Copying objects class MyClass { public $var = 1; } obj1 object obj2 obj1 obj2 $obj1 = new MyClass(); $obj2 = $obj1; $obj2->var = 2; print $obj1->var; //print 2 object object $obj1 = new MyClass(); $obj2 = clone $obj1; $obj2->var = 2; print $obj1->var; //print 1 Access protection of member variables class MyDbConnectionClass { public $queryResult; protected $dbHostname = "localhost"; private $connectionHandle; // ... } class MyFooDotComDbConnectionClass extends MyDbConnectionClass { protected $dbHostname = "foo.com"; } Example class Person { private $name; function setName($name) { $this->name = $name; } function getName() { return $this->name; } }; $judy = new Person(); $judy->setName("Judy"); $joe = new Person(); $joe->setName("Joe"); print $judy->getName() . "\n"; //print Judy print $joe->getName(). "\n"; //print Joe Static properties class MyUniqueIdClass { self: refer to the current class static $idCounter = 0; public $uniqueId; function __construct() { self::$idCounter++; $this->uniqueId = self::$idCounter; } } $obj1 = new MyUniqueIdClass(); print $obj1->uniqueId ; //print 1 $obj2 = new MyUniqueIdClass(); print $obj2->uniqueId ; //print 2 POLYMORPHISM • Single class inheritance – like Java • Multiple interface implementations – Final keyword class Child extends Parent { ... } class A implements B, C, ... { ... } interface I1 extends I2, I3, ... { ... } <?php class Auth { function Auth() { mysql_connect('localhost', 'user', 'password'); mysql_select_db('my_own_bookshop'); } public function addUser($email, $password) { $q = ' INSERT INTO users(email, passwd) VALUES (“ '. $email. ‘ ", “ '. sha1($password).‘ ") '; mysql_query($q); } public function authUser($email, $password) { $q = ' SELECT * FROM users WHERE email=“ '. $email. ' " AND passwd =“ '. sha1($password). ' " '; $r = mysql_query($q); if (mysql_num_rows($r) == 1) { return TRUE; } else { return FALSE; }}} ?> Reflection • Allows to have class information at run-time • Just an example <?php class C { function F() { print "Hello, World\n"; } } ReflectionClass::export("C"); ?> … - Constants [0] { } - Static properties [0] { } - Static methods [0] { } - Properties [0] { } - Methods [1] { Method [ public method F ] … PHP Communication string file_get_contents ( string $filename [ …]) Reads entire file into a string <?php /* Identical to above, explicitly naming FILE scheme */ $localfile = file_get_contents("file:///home/bar/foo.txt"); /* Read remote file from www.example.com using HTTP */ $httpfile = file_get_contents("http://www.example.com/foo.txt"); /* Read remote file from www.example.com using HTTPS */ $httpsfile = file_get_contents("https://www.example.com/foo.txt"); /* Read remote file from ftp.example.com using FTP */ $ftpfile = file_get_contents("ftp://user:pass@ftp.example.com/foo.txt"); /* Read remote file from ftp.example.com using FTPS */ $ftpsfile = file_get_contents("ftps://user:pass@ftp.example.com/foo.txt"); ?> Example • Flickr is a web site that allows to share personal photos • Free account for 90 days • API with different formats – Request: REST,XML-RPC,SOAP – Reply: REST,XML-RPC,SOAP,JSON,PHP Flickr’s application end-points • • • • • http://api.flickr.com/services/rest/ http://api.flickr.com/services/soap/ http://api.flickr.com/services/xmlrpc/ http://api.flickr.com/services/upload/ http://api.flickr.com/services/replace/ REST format is the simplest way; it uses the HTTP POST method end-point-type http://api.flickr.com/services/rest/?method=...&name=value... CLIENT SERVER Reply, different format: REST,XML-RPC,SOAP,JSON,PHP PHP_Serial Example of API call flickr.photos.getInfo In Parameters: api_key (Mandatory) Your API application key. photo_id (Mandatory) The id of the photo to get information for. secret (optional) The secret for the photo. If the correct secret is passed then permissions checking is skipped, unless photo is shared. Out Parameters: info with different format… Example of reply An example: invoking a REST end-point from PHP code $param = array( 'api_key' => 'method' => 'photo_id' => 'format' => ); $encoded_params = array(); 'e568d81ac2ac47e943673641e037be8 c', 'flickr.photos.getInfo', '11111', 'php_serial', foreach ($param as $k => $v) $encoded_params [ ] = urlencode($k).'='.urlencode($v); $url = "http://api.flickr.com/services/rest/?".implode('&',$encoded_params); Parameters •Reply in php serial format urlencode •non-alphanumeric as % sign two hex digits •spaces as plus (+) signs. implode •Join array elements with a string, •& used as glue string $url http://api.flickr.com/services/rest/?api_key=e568d81ac2ac47e943673641e037be8&method=flickr.photos.getInfo&photo_id=11111&format=php_serial Serialization string serialize ( mixed $value ) Generates a storable representation of a value mixed unserialize ( string $str ) Creates a PHP value from a stored representation Invoke method Transform format into an associative array $ans = file_get_contents($url); $ans_obj = unserialize($ans); if ($ans_obj['stat']=='ok') { echo $ans_obj['photo']['id'].'<br>'; echo $ans_obj['photo']['title'] ['_content']; echo $ans_obj['photo']['description']['_content']; echo $ans_obj['photo']['dates']['taken']; }