Presentation is loading. Please wait.

Presentation is loading. Please wait.

UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 3 PHP (2) : Functions, User Defined Functions & Environment Variables.

Similar presentations

Presentation on theme: "UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 3 PHP (2) : Functions, User Defined Functions & Environment Variables."— Presentation transcript:

1 UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 3 PHP (2) : Functions, User Defined Functions & Environment Variables

2 last lecture … o PHP origins & use o Basic Web 1.0 2-tier/3-tier architecture with PHP o PHP as a scripting language (supporting procedural & oo paradigms) o Basic structure & use (statements, variables, control structures, operators) o PHP data types - 5 basic – integer, floating-point, string, boolean & NULL & 3 complex - array, hash & object o the exit() & die() statements

3 PHP Functions (1) : inbuilt function library (700+) o Basic tasks –String Handling –Mathematics – random numbers, trig functions.. –Regular Expressions –Date and time handling –File Input and Output o And more specific functions for - –Database interaction – - MySQL, Oracle, Postgres, Sybase, MSSQL.. –Encryption –Text translation –Spell-checking –Image creation –XML etc.etc.

4 PHP Functions (2) : some commonly used built-in functions FunctionPurposeExample echo() prints text echo "Hello World"; explode() returns a string as an array split on the specified delimiter $pizza = "piece1 piece2 piece3"; $pieces = explode(" ", $pizza); echo $pieces[1]; // piece2 implode() opposite of explode – joins all the elements of an array using the specified delimiter $array = array('lastname', 'email', 'phone'); $comma_separated = implode(",", $array); //prints lastname,email,phone echo $comma_separated; isset() returns TRUE if a variable exists or FALSE if not isset($a); fopen() opens a file for reading (“r” ) or (“w”) writing. Use in conjunction with fclose. $filename = " myfile.txt " ; $handle = fopen($filename, " r " ); $contents = fread($handle, filesize($filename)); fclose($ini_handle);

5 PHP Functions (3) : user defined functions o Declaring a function - functions are declared using the function statement, a name and parenthesis () e.g function myfunction() {…..} - functions can accept any number of arguments and these are separated by commas inside the parenthesis e.g function myFunction(arg1, arg2) {…..} - the following simple function prints out any text passed to it as bold <?php function printBold($text){ print(" $text "); } print("This Line is not Bold \n"); printBold("This Line is Bold"); print(" \n"); print("This Line is not Bold \n"); ?> run example

6 o the return statement - at some point the function will finish and is ready to return control to the caller - execution then picks up directly after the point the function was called - it is possible to have multiple return points from a function (but this will reduce code readability) - if a return statement includes an expression, return(expression), the value of the expression will be passed back - example: <?php function makeBold($text){ $text = " $text "; return($text); } print("This Line is not Bold \n"); print(makeBold("This Line is Bold"). " \n"); print("This Line is not Bold \n"); ?> PHP Functions (4) : user defined functions run example

7 - values and references - for most data types, return values are passed by value - for objects, return values are returned by reference - the following function creates a new array of 10 random numbers between 1 and 100 and passes it back as a reference <?php function &getRandArray() { $a = array(); for($i=0; $i<10; $i++) { $a[] = rand(1,100); } return($a); } $myNewArray = &getRandArray(); print_r($myNewArray); ?> PHP Functions (5) : user defined functions run example

8 - scope (1) - scoping is way of avoiding clashes between variables in different functions - each code block belongs to a certain scope - variables within functions have local scope and are private to the function - variables outside a function have a global scope <?php $a = 1; /* global scope */ function test(){ echo $a; /* reference to local scope variable */ } test(); ?> The above example will output nothing because the $a inside the function has local scope PHP Functions (6) : user defined functions

9 - the global keyword can be used to access variables from the global scope within functions <?php $a = 1; $b = 2; function Sum(){ global $a, $b; $b = $a + $b; } Sum(); echo $b; ?> - The above script will output 3. By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function. PHP Functions (7) : user defined functions run example

10 - arguments - functions expect arguments to to be preceded by a dollar sign ($) and these are usually passed to the function as values - if an argument has a & sign in front - it is treated as a reference - the following example shows an argument passed as reference <?php function stripCommas(&$text){ $text = str_replace(",", "", $text); } $myNumber = "10,000"; stripCommas($myNumber); print($myNumber); ?> PHP Functions (8) : user defined functions run example

11 -default values - a function can use a default value in an argument using the = sign to precede the argument - consider the following example <?php function setName($FirstName = "John", $LastName = "Smith"){ return "Hello, $FirstName $LastName!\n"; } ?> - So, to greet someone called John Smith, you could just use this: setName(); - To greet someone called Tom Davies, you would use this: setName("Tom", "Davies"); - To greet someone called Tom Smith, you would use this: setName("Tom"); PHP Functions (9) : user defined functions

12 Environment & other predefined variables (1) o PHP provides a large number of predefined variables to all scripts. o These variables represent everything from external variables to built-in environment variables, last error messages to last retrieved headers.external variables $GLOBALS $GLOBALS — References all variables available in global scope $_SERVER$_SERVER — Server and execution environment information $_GET$_GET — HTTP GET variables $_POST$_POST — HTTP POST variables $_FILES$_FILES — HTTP File Upload variables $_REQUEST$_REQUEST — HTTP Request variables $_SESSION$_SESSION — Session variables $_ENV$_ENV — Environment variables $_COOKIE$_COOKIE — HTTP Cookies $php_errormsg$php_errormsg — The previous error message $HTTP_RAW_POST_DATA$HTTP_RAW_POST_DATA — Raw POST data $http_response_header$http_response_header — HTTP response headers $argc$argc — The number of arguments passed to script $argv$argv — Array of arguments passed to script

13 o Some predefined variables are available to every script in every scope (both local and global) and these are referred to as Superglobals.Superglobals o For these, there is no need to do global $variable ; to access them within functions or methods. o The superglobals are: Environment & other predefined variables (2) $GLOBALS $_SERVER $_GET $_POST $_FILES $_COOKIE $_SESSION $_REQUEST $_ENV

14 Environment & other predefined variables (3): the $_REQUEST, $_GET & $_POST globals o The most commonly used global variables are $_GET and $_POST which are used to send data from the browser to the server. o $_GET is an associative array (hash) that passes values to the current script using URL parameters. - although the HTTP protocol does not set a limit to how long URL’s can be – different browsers do – so it is considered good practice not to send data that is more than 2000 characters with $_GET - because the values of $_GET can be read in the URL – no data containing sensitive information (like passwords) should be sent using $_GET - $_GET can't be used to send binary data, like images or word documents, just textual data.

15 Environment & other predefined variables (4): $_GET example <?php if(isset($_GET["name"]) || isset($_GET["age"])) { echo " Welcome ". $_GET['name']. " "; echo "You are ". $_GET['age']. " years old. "; exit(); } ?> " method="GET"> Name: Age: checks if either the ‘name’ or ‘age’ params. have values set html form with 3 inputs form method set to ‘GET’ $PHP_SELF returns path and name of current script ** Notice that once the form fields are filled in with values of say ‘Popeye’ and ‘83’, the URL shows as http://host/path/function_example_6.php?name=Popeye&age=83 i.e. the parameters are now part of the URL. view script run script

16 o The POST method transfers information via HTTP headers. - the POST method does not have any restriction on data size to be sent. - it can be used to send ASCII as well as binary data. - the data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP (HTTPS) the data can be secured (to a certain extent). - PHP provides the $_POST associative array to access all the sent data using the POST method. ** Note that the example used in the previous slide can be easily changed to make use of the POST method by simply changing the method="GET" to method="POST". The parameters no longer appear in the URL. o $_REQUEST is an associative array (hash) that by default contains all of the contents of $_GET, $_POST and $_COOKIE together. ($_COOKIE superglobal will be discussed when we consider PHP sessions).array$_GET$_POST$_COOKIE Environment & other predefined variables (5): $_POST & $_REQUEST view scriptview script run scriptrun script

Download ppt "UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 3 PHP (2) : Functions, User Defined Functions & Environment Variables."

Similar presentations

Ads by Google