Some example ������������������������������ �������������������������������� ��������� ��������������������������������� ������������������� ���������������������� ������������������� ���������������������� ���������� ����!���"�����������������#���"��� ���������� ����������� ������������ ������$���������������$ ���� ����� ���%��& ���� ���'�
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) 1.2.php
echo statement • To achieve newlines in browser, use appropriate tagging • Use \ to escape (negate) the effect of the following character 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
print_r() • print_r() can be used to "dump" variable output, typically for debugging of complex structures. <?php echo "<pre>"; print_r($_SERVER); echo "</pre>"; ?>
Comments • Multi-line comments /* This is a multi-line comment */ • Single line comments // This single line is commented // 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.
Constant • Unchangeable values. In all caps by convention. No $. <?php define('MYCONST',100); define('NAME',"My Name"); 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())
Variable’s scope • Names inside a function has local scope • Script level names can be accessed through the special built- in array $GLOBALS $m $m main script main script function Af $a is only visible in the function Af’s scope $a $m can be seen via GLOBALS[‘m’] 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 run- time environment and available to the script. • Superglobals are key to form processing, 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.
Example • What’s this code doing? <?php echo '<pre>'; print_r($GLOBALS); print_r($GLOBALS); echo '</pre>'; ?>
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.
Example <?php $user = (isset($_GET[‘user’]))? $_GET[‘user’]: ‘’; … ?>
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
Variable variables <?php $name = "John"; $$name = "Registered user"; print $John; //display “Registered user” ?> ?> John Registered user $name $$name (=$John)
Conditional control structures �� � ���� � ���� ���� �) �����(��� �����(�������� ������ � ���� � ������ � ���� ��) �����(��� �����(�������� ������ � ���� � �����(��� ��� ��� �����) �����) ���� ���� �����(�������� �����(��� ������ 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 #%��� � ���� � #%��� � ���� ��) �� ����& � �����(�������� ��������� ����& ����� �����(��� ���#%���� #%��� � ���� �� ������"� � ������"� ����� ��� ��* �!��* �!�+���* �!��* �!�+���* �!��* �!�+� �����(��� �����(��� for ($i = 0; $i <= count($array); $i++) { } $count = count($array); for ($i = 0; $i <= $count; $i++) { }
'���� • ����������������� ������������������������������ • '������������������������������������������������������� ����������� • (��������������������� – ��������� ��������� • ��)�������� • *�����#������ • �����#�)�� • ��#���� – �����������+���������������,
���������� 1�������(�)� ,�� "���� ��-��*�-���(��-�������(�-/�,��/� 2������(�)� ,�� "���� ��-��*�-���(��-������(�-/�,��/,��/ ,�� "���� ��-�����-���(��-��*-�.��"��-(���-/�0����,��/ ,�� "���� ��-�����-���(��-��*-�.��"��-��(���-/�1�(����,��/,��/ 4�%�.������&�)� ,�� "���� ��-�%��&��*-���(��-.�%����-�.��"��-5�&�-/�,��/� 4�%�.�������)� ,�� "���� ��-�%��&��*-���(��-.�%����-�.��"��-6��-/�,��/ ,�� "���� ��-�"�(��-���(��-3"�(��-�.��"��-��-/�,��/
'������#������� ,���(���(��-�� "�-� ������ �- ������� % -� �����$ �-���-/ ���.�� ���#��� �������(�%�(� �� �� ���� ������� % �� �� %�� )�������%���� �������%�(�7�������(��89������(��59��*�(���9.�%�����5�&�93"�(�����
������#�� ,����� �������-�-/ ��������������� ,��/� �������������# ,��/��#��!�������,���/� ,��/��#��!������:,���/� ,���/� ,��/� ,��/��#�:!�������,���/� ,��/��#�:!������:,���/� ,���/ ,������/�
Exercise • Write a simple php program that displays the Pitagora’s table. The size of the table is a parameter passed through a form..
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. 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. • Long GET strings may be problematic. • 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 URL to recall the script with the same data is not possible. • Large POST packets not a problem. • On most browsers, hitting 'refresh' causes post data to be retransmitted. • Data available into the $_POST superglobal
����)����� ,%�(�/ ,%���/,�����/;�������,������/,�%���/ ,����/ ,%�/;�����������,�%�/ �����������$(!���!�������(!���� ���)���!� ,�����/ ,��/��� ,��/��� ,��/<=(�����������),���/�,��/� ����*���+��(,��-�,�����(,�����,�� ,���/�,���/ ,��/<=(�����������),���/�,��/� ����*���+��(,��-�,�����(,�����,�� ,���/�,���/ ,��/ ,��/1�������(�),���/�,��/,�� "���� ��>��*�>���(��>�����$��(�>�/,���/� ,���/ ,��/ ,��/2������(�),���/�,��/,�� "���� ��>��*�>���(��>����$��(�>�/,���/,���/ ,��/ ,��/?���#���),���/�,��/� ����*���+��(,�� ���$,�����(,�� ���$,�� ,���/,���/ ,��/ ,������� ���>:>/� ����*���+��(, *.���,�����(,���� ���,�/��*�(,0��� ���,��� ,���/�,���/ ,������/ ������� ,�����/ ,�%�(�/
����)����� ������ ,%�(�/ ���������� ,%���/,�����/;�������,������/,�%���/ ������ ,����/ ,%�/;�����������,�%�/ ����� �����$(!���!�������(!���� ���)���!� ,�����/ ,��/��� ,��/��� ,��/<=(�����������),���/�,��/� ����*���+��(,��-�,�����(,�����,�� ,���/�,���/ ,��/<=(�����������),���/�,��/� ����*���+��(,��-�,�����(,�����,�� ,���/�,���/ ,��/ ,��/1�������(�),���/�,��/,�� "���� ��>��*�>���(��>�����$��(�>�/,���/� ,���/ ,��/ ,��/2������(�),���/�,��/,�� "���� ��>��*�>���(��>����$��(�>�/,���/,���/ ,��/ ,��/?���#���),���/�,��/� ����*���+��(,�� ���$,�����(,�� ���$,�� ,���/,���/ ,��/ ,�� ���� ���>:>/� ����*���+��(, *.���,�����(,���� ���,�/��*�(,0��� ���,��� ,���/�,���/ ,������/ ������� ,�����/ ,�%�(�/ ����������
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? 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(“…”) • Even if the number of options are known, check the actual value is a best practice… why?
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 # 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=‘’ ”;
Preventing • Every time you give user chance to enter data, you MUST check to be sure not trying to manipulate your application. Create and use a clean() function like this function clean($input, $maxlength) { $input = trim($input) $input = substr($input,0,$maxlength); $input = substr($input,0,$maxlength); $input = escapeShellCmd($input); $input = htmlspecialchars($input,ENT_QUOTES); return $input; } • escapeshellcmd() escapes characters that might be used to trick a shell command into executing arbitrary commands. • htmlspecialchars() prevents user-supplied text from containing HTML markup.
Self referencing Sticky form • Form display and form processing can be consolidated into one script. • Requiring a user to retype all form data in event of error/omission reduces usability. • Allows " sticky form ": display error message to • Allows " sticky form ": display error message to user and also retain values the user has already entered. • Design (at minimum): – Form validity checking embedded on page with form. – Form submits to itself for processing. Typically done using PHP superglobal $_SERVER[PHP_SELF] .
Sticky form pseudo-code • If form submitted: – Check validity – If not valid display the form back again with field set set • Send the form
Gluing script Check ok Script1 Script2 Script2 Check nok
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)) "Barbara", "age" => 67)) 1 and 2 are same, 3 and 5 are same, 6 is a nested array
Examples 8���� ���������������!�:!���� � ����:@�A����� @�A��/�� print_r($arr1) ����:@�A���:� @�A��/�: ����:@:A����� @:A��/�� � � ��������������-��(�-��/�-B�%�-!�-���-��/� :C�� ��������������:������%����(� ����:@-��(�-A���-B�%�-� ����:@-���-A���:C� �����������������:��D �����>��������������:������%����(�>� E
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 • � ����������������-B�%�-!�-5������-!�-5���-!�-F����-�� The players are: #0 = John �����-G%�� ����������),��/-� #1 = Barbara ������% �� �����������&����/��.��"���D #2 = Bill �����-H�&������.��"�,��/-� #3 = Nancy E
Exercise • Format the output of the players as a html table
Exercise ,7 % � ����������������-B�%�-!�-5������-!�-5���-!�-F����-�� �����>G%�� ����������,��/,�������������-�-/>� ������% �� �����������&����/��.��"��� D ������,������$�,)!12�+!),���$���$�,)!1/��*�!),���$������, � ������,������$�,)!12�+!),���$���$�,)!1/��*�!),���$������, � E �����>,������/> 7/ concat double quoted to replace $key with its value
list, each � ���������������-B�%�-!�-5������-!�-5���-!�-F����-�� ������� �������� #%�����������&��!��.���������%�� ���������D �����-H�&������.��-� E list() assigning multiple array elements each() returns the current key/value pair to multiple variables in one statement as an array with four elements: the elements 0, "key", 1 and "value"
LAB • LAB1. – Scrivere uno script che costruisca la tabella di Pitagora n x n • LAB2. Sticky form – Scrivere uno script che genera un form per l’inserimento di nome e cognome. Se i due campi non sono completi rigenera una form con i valori nei campi rimempiti una form con i valori nei campi rimempiti • LAB 3. – Scrivere una generica funzione di “sanity check”, che a partire da un vettore ‘signature’ contentente tipo, caratteristica dei campi della form (required o meno) e nome funzione: • controlli se tutti i campi di una form sono stati riempiti • Converta I tipi come specificato • Applichi una funzione a tutti gli argomenti
Functions • Any valid PHP code may appear inside a user- defined function, even other function… • Functions need not be defined before they are referenced 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”) 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>”;} function foo() {echo “in foo()<br>”;} Function bar($arg = ‘’) { echo “in bar(); argument was $arg”<br>”; } $func = ‘foo’; $func(); #call foo() $fun = ‘bar’; $func(‘test’);
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 • … •
Closure • Closure allows to define an anonymous function <?php $out = array_map(function ($a){return 2*$a;},$in); $out = array_map(function ($a){return 2*$a;},$in); ?> <?php $double =function ($a){return 2*$a;}; $out = array_map($double,$in); ?>
Exercise: generic sanity check function • Design a function that parametrically checks – if all required fields are set – Type convert values
Code inclusion control structures ����*$� ��������� � ����"������������� ����*$�3���� ��������� � ��4*��� ��������� � ��4*��� ��������� � ��I"���)���� ���������.������� ��I"���)���� ���������.������� ��4*���3���� ��������� � ����"��� ��� � ��� ��������������� ������ include "http://www.example.org/example.php"; include $_SERVER["DOCUMENT_ROOT"] . "/myscript.php";
Eval • Include/require actually “execute” the included script • Eval, allows to dynamically execute php string code code
Persistency • Cookie, Session – Per browser data storage, no cross-browser data exchange • File, DB File, DB – Site level persistence storage
������ ������������������������ ����������� ������������������������������� • �����+#������,�������������������� ��#���������������#������������������ • �������������� ���������� �����+��)��������-./0�#����, • ������������#�������������������������������������� • �����������������+�������������,������������������ �����������������+�������������,������������������ • •
������ ������������������������ ����������� ������������������������������� • �����+#������,�������������������� ��#���������������#������������������ • �������������� ���������� �����+��)��������-./0�#����, • ������������#�������������������������������������� • �����������������+�������������,������������������ �����������������+�������������,������������������ • • Header sent from the client to the server http header sent from the server to the client ���56��2��%� 6��2��%� �0�(��7��7����6��87�'� �0�(��7��7����6��87� �-���� (��*"9:5��+5;<9;�<<%<<%<<�=��' �����(��'�$�����()$� )*������9)��
Inspecting http header • Browsers can install plug-in to inspect http headers • For example, liveHTTPHeader for firefox
����������� � Output must be buffered ,7 % �.3 ����>?'� 7/ 7/ ,%�(�/ ,%���/,�����/6��&����*�( ��,������/,�%���/ ,����/ ,7 % �����2��>�+6��2��",����,? 7/ ,�����/ ,�%�(�/ 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[inc])): $Counter++; endif; if (isset($_POST[dec])): $Counter--; endif; print "Counter=$Counter"; setcookie(C,$Counter); endif; ?> </BODY> </HTML>
Tic Tac Toe P=P1, enters for the first time Set Cookie P1 display “Wait” Player Display P=P1, returns, P2 not entered enters Form display “Wait” Player arrives arrives Index SYNC P=P1, returns, P2 entered redirect Display Form P=P2 Set Cookie P2 redirect P = Player P1 = First Player that arrives P2 = Second Player
Tic Tac Toe Display new view move PLAY 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 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
Recommend
More recommend