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) • Double quote “ sends variable value (line 4) <?php $a=6; 1 echo $a; 2 echo 'The var name is $a'; 3 echo "The var contains $a"; 4 ?> 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 <?php $a=6; echo "She said, \ "How are you? \ ""; echo $a; echo "<a href= \ "page.htm \ ">link</a>"; echo 'The var name is $a' . '<br>' ; ?> echo "The var contains $a"; 1.4.php ?> 1.3.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 – 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.open("GET", URL+document.getElementById('inputText').value, true); request.send(null); request.onreadystatechange = do_it; } open method used for preparing the request do_it is the event listener for the reply send sends the request <?php echo $_GET['char']; ?> php script
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 – 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; 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"> server browser 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 Send data information PHP Script PHP Script (form DB access processing) Send html output .html back of results
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 – 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> <tr> <td>E-mail address:</td> <td> <input type='text' name='email'/> </td> </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 <html> method <head><title>Register</title></head> Processing <body> script <h1>Registration</h1> <form method="get" action="register.php"> <table> <tr> <tr> <td>E-mail address:</td> <td> <input type='text' name='email'/> </td> </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®ister=Register
Input validation • Never assume a form: – is filled out completely – Contains the type of information requested – Has been submitted by a benign user – 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 • 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 ) if ( expr ): statement statement list { statement1; elseif ( expr ) statement 2; elseif ( expr ) : statement } statement list elseif ( expr ) statement ... ... else : else : else statement list statement endif; if ($num<0) <?php if ($num < 0): ?> print '<h1>$num is negative</h1>'; <h1>$num is negative</h1> elseif ($num==0) <?php elseif($num == 0): ?> print '<h1>$num is zero</h1>'; <h1>$num is zero</h1> else <?php else: ?> print '<h1>$num is positive</h1>'; <h1>$num is positive</h1> <?php endif; ?>
Traditional loop control structures while ( expr ) while ( expr ) : do statement list statement statement endwhile; while ( expr ); for (expr, expr, …; expr, expr, …; expr, expr, …) statement statement for ($i = 0; $i <= count($array); $i++) { } $count = count($array); for ($i = 0; $i <= $count; $i++) { }
Html table <table border="1"> td = table data <tr> tr = table row <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>
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. array(1, 2, 3) 2. array(0 => 1, 1 => 2, 2 => 3) 3. array ("name" => "John", "age" => 28) 4. array(1 => "ONE", "TWO", "THREE") 5. array(1 => "ONE", 2 =>"TWO", 3 => "THREE") 6. 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 Array $arr1 = array(1, 2, 3); ( $arr2[0] = 1; [0] => 1 $arr2[1] = 2; print_r($arr1) [1] => 2 $arr2[2] = 3; [2] => 3 ) ) $arr1 = array("name" => "John", "age" =>28); $arr2["name"] = "John"; $arr1 and $arr2 are the same $arr2["age"] = 28; if ($arr1 == $arr2) { print '$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"); The players are: #0 = John print "The players are:<br>"; #1 = Barbara foreach ($players as $key => $value) { #2 = Bill print "#$key = $value<br>"; #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 next and each each to access the array elements – next gives us the next value next value with each call • It moves moves to the next item, then returns 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 key field for the current key – A value 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"]; $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 – 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 TRIS.php 0 CLIENT SERVER Cells labeled fron 0 to 8 8
2 players • More complex: login(?), synchronization, store the state 1. Initialize TRIS SERVICE 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 1. Initialize TRIS SERVICE 1. Wait for my turn 2. Update the local state turn.txt move.txt 3. Make the move write read getTurn Player 1 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 user- defined 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) function square($n) { { $n = $n*$n; $n = $n*$n; } } … by-reference
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); 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;}; 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 only once include_once file_name ; require file_name ; require file_name ; require: stop if not available 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";
Recommend
More recommend