lec002

Upload: neolithic-ravian

Post on 12-Oct-2015

12 views

Category:

Documents


0 download

DESCRIPTION

VU Lectures

TRANSCRIPT

  • Web Application Development

    Using

    PHP MYSQL

    EVS Professional Training Institute

    http://www.evslearning.com/ +92-42-111-685-822 +92-51-111-685-822

    Compiled By

    Kashif Umar

    [email protected]

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 2 of 29

    Week 1 Lecture 2

    Functions Functions are self-contained units of a program

    designed to accomplish a specified task such as calculating a mortgage payment, retrieving data from a database, or checking for valid input.

    When a function is called in a program, it is like taking a detour from the main part of the program.

    PHP starts executing the instructions in the function, and when finished, returns to the main program and picks up where it left off.

    Functions can be used over and over again and thus save you from repetitious programming.

    They are also used to break up a program into smaller modules to keep it better organized and easier to maintain.

    By definition, a function is a block of statements that not only performs some task, but can also return a value.

    A function is independent of your program and not executed until called.

    A function, often referred to as a black box, is like the pocket calculator or remote control. Information goes into the black box as input (like the calculator or remote control when you push buttons), and the action or value returned from the box is its output (such as a calculation or a different channel). What goes on inside the box is transparent to the user. The programmer who writes the function is the only one who cares about those details.

    When you use PHPs built-in functions such as print() or rand(), you send a string of text or a number to the function, and it sends something back. You do not care how it does its job, you just expect it to work. If you send bad input, you get back bad output or maybe nothing.

    Functions are like miniscripts. They contain PHP statements that behave as a single command and can be called repeatedly throughout a program without rewriting the code.

    The terms function and method are often used interchangeably.

    The term method refers to a function that is used with PHP objects.

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 3 of 29

    The term function is a stand-alone block of statements, independent of the program until invoked by a caller.

    User Defined Functions Defining and Calling Functions

    A simple function is defined as follows. Syntax

    function myfunct() {

    do this; do that; do this other thing; }

    Like built-in functions, user functions can receive parameters. To define a function with parameters, place receiving variables in the parentheses.

    Syntax

    function addNums($param1, $param2, $param3) {

    $sum = $param1 + $param2 + $param3; echo 'The sum is ' . $sum;

    }

    User functions can also return values.

    Syntax

    function addNums($param1, $param2, $param3) { $sum = $param1 + $param2 + $param3; return $sum; }

    User functions are called in the same way that built-in functions are. For example, the following code calls the addNums() function to get the sum of three numbers.

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 4 of 29

    Syntax $total = addNums(1,3,5);

    Default Values You can make function parameters optional by assigning default values to them as shown in the example below. Code Sample: DefaultValues.php

    Simple User-defined Function

    Code Explanation In this case, if you don't pass a value into the function for one or more of the parameters, the default value of 0 will be used. When defining a function, all required parameters should precede optional parameters.

    Variable Scope In PHP, variables declared outside of functions are not available by default inside of functions. The following code illustrates this:

    Code Sample: LocalVars.php

    Local Variables

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 5 of 29

    To make the variables available to the function, they must be declared within the function as global variables using the global keyword.

    Code Sample: GlobalVars.php

    Global Variables

    By Reference vs. By Value

    By default, variables are passed to functions by value, meaning that the function's receiving

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 6 of 29

    variables get copies of the values received rather than pointers to them. If the receiving variables are modified, the passed variables remain unaffected. The following code illustrates this.

    Code Sample: ReusingCode/Demos/ByValue.php

    By Value

    The above code outputs "10" to the browser. Although $num was incremented by 5, $a was unaffected by the function call. To pass a variable by reference, put an ampersand (&) before the parameter in the function definition. Code Sample: ByReference.php

    By Reference

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 7 of 29

    incrNumBy($a,$b); echo $a; //outputs 15 to the browser ?>

    This time the function outputs "15" because $num references the variable $a itself. So, any change in $num will affect $a.

    Nesting Functions

    PHP supports nesting functions. A nested function is defined and called from within another function. The outer function, also called the parent function, has to be invoked for the nested function to become available to the program. Nested functions are rarely used. OuterFunction() must be called before NestedFunction() is available.

    PHP functions can also be nested inside other statement blocks, such as conditional statements. As with nested functions, such functions will only be defined when that block of code has been executed.

    Example

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 8 of 29

    Built-In Functions

    Math Functions

    echo("round : " . round($myFloat) . ""); echo("round : " . round($myFloat, 1) . ""); echo("Ceiling : " . ceil($myFloat) . ""); echo("Floor : " . floor($myFloat) . ""); echo("Absolute Value : " . abs(0 - 300) . ""); echo("Exponential : " . pow(2, 8) . ""); echo("Square root : " . sqrt(100) . ""); echo("Modulo : " . fmod(20, 7) . ""); echo("Random (any) : " . rand() . ""); echo("Random (min, max) : " . rand(1, 10) . "");

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute

    http://www.evlearning.com/

    Page 9 of 29

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute

    http://www.evlearning.com/

    Page 10 of 29

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute

    http://www.evlearning.com/

    Page 11 of 29

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute

    http://www.evlearning.com/

    Page 12 of 29

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 13 of 29

    String Functions Lowercase :

    Uppercase :

    Uppercase first-letter :

    Uppercase words :

    Length :

    Trim :

    Find :

    Replace :

    Repeat :

    Substring :

    String Position :

    Char Position :

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 14 of 29

    Making Function Libraries We can make a separate php file of our commonly used

    user-defined function and treat them as libraries. PHP provides two common constructs for including files in web pages: require and include. They are basically the same with one minor difference. require throws a fatal error when it fails; whereas, include only gives a warning. If you need the included file to continue to process the page, you should use require. It is important to keep in mind that a PHP tag cannot start in a calling file and continue in an included file. All PHP code in the included file must be nested in PHP tags. include require

    require is not actually a function, but a language construct, so require statements can be written in two ways:

    Syntax require(path_to_file); require path_to_file; path_to_file can be an absolute or a relative path.

    require_once

    require_once can be used just like require. The difference is that if the included file has already been included by earlier code, it will not be re-included.

    A Note on Security

    If included files are under the web root, they can be accessed just as any other file can. If they have an extension such as inc then the browser may display them as plain text. With other extensions, the browser may attempt to download the file. If the included file is a PHP file and a user navigates to it, the server will try to process the file and may return errors. As a precaution, you may want to place your included files in a directory above or outside of the web root. This will prevent users from accessing the files directly.

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 15 of 29

    include_path directive

    The php.ini contains an include_path directive, which takes a semi-colon delimited list of paths to directories that PHP should look in for included files. ; UNIX: "/path1:/path2" ;include_path = ".:/php/includes" ; ; Windows: "\path1;\path2" ;include_path = ".;c:\php\includes" include_path = ".;C:\Programs\xampp\php\PEAR;../../../../" Here is a code sample that demonstrates how to include files using require. Code Sample: Require.php Including Files This text is on the main page.

    Code Explanation

    The above code is relatively straightforward. Require.php contains two included (required) files: Required.php and Required.inc. Notice that there is PHP code inside of Required.inc, which is executed. The extension of the included files does not affect how the code inside the files will be executed.

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 16 of 29

    auto_prepend_file and auto_append_file The configuration file, php.ini, contains settings for automatically prepending and appending files to every PHP script. These settings are auto_prepend_file and auto_append_file. By default, they contain no values; however, they can be set to point to a files using absolute paths as follows:

    ; Automatically add files before or after any PHP document. auto_prepend_file = "c:/inetput/include/runbefore.inc" auto_append_file = "c:/inetput/include/runafter.inc"

    The auto_prepend_file directive can be used to application-wide variables such as database connection strings or common file paths. The auto_append_file directive can be used for cleaning up code or for outputting debugging information to the browser.

    Note that it is not possible to set different auto-prepend and auto-append files for different directories or different scripts.

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 17 of 29

    Arrays A variable that stores one value is called a scalar

    variable, whereas an array is a variable that can store a collection of scalars, such as an array of numbers, an array of strings, an array of images, colors, and so on. If you want to define one number you would store it in a simple scalar variable, but if you want to store a whole list of numbers, it would be more practical to use an array, and give the array a name to represent all of the numbers. Otherwise, you would have to create individual scalars for each number. It would be hard to come up with individual names for, lets say, 100 numbers, or even for 10 numbers, but with an array you can use one name to reference all of them. Based on how the individual elements are there are two types of arrays in PHP.

    Indexed Array

    Referenced Array

    Indexed Array Indexed arrays are similar to tables with a single

    column. An indexed array can contain zero or more elements. In PHP, like in many programming languages, the first element of an array is in the "zeroeth" position. An array with no elements has a zero length.

    Initializing Arrays

    Arrays are initialized with the array() function, which can take a list of comma-delimited values that become the elements in the new array. The following lines of code initializes a zero-length array and then adds four elements to the array. Syntax $topics = array(); $topics[0] = 'HTML'; $topics[1] = 'CSS'; $topics[2] = 'JavaScript'; $topics[3] = 'PHP';

    The first line above is actually optional as the second line will create the array if one does not already exist. However, it is a better coding practice to explicitly initialize the array. The

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 18 of 29

    $topics array could also be created in a single line as follows.

    Syntax $topics = array('HTML','CSS','JavaScript','PHP');

    Appending to an Array

    If you know how many elements are in an array, you can append to the array by specifying the index. For example, you could append to the $Beatles array shown above as follows:

    Syntax $topics[5] = 'MySQL'; However, sometimes you don't know how many elements are in an array. Although you can easily figure this out, doing so requires an extra step. PHP provides an easy way of appending to an array of any length. Simply leave out the index.

    Syntax

    $topics[] = 'MySQL';

    Reading from Arrays

    Reading from arrays is just a matter of pointing to a specific index or key.

    Syntax echo ($topics[2]; //outputsJavaScript to the browser

    Looping through Arrays

    The following code will loop through the entire $topics array outputting each element to the browser.

    Syntax for ($i = 0 ; $i < count($topics) ; $i++) {

    echo "$topic"; }

    OR

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 19 of 29

    foreach ($topics as $topic) {

    echo "$topic"; }

    The above code snippets are combined in the following example.

    Code Sample: IndexedArrays.php Indexed Arrays Indexed Arrays

    Referenced/Associative Array Whereas indexed arrays are indexed numerically, associative arrays are indexed using names. For example, instead of JavaScript being indexed as 3, it could be indexed as "clientSideScript". Initializing Associative Arrays

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 20 of 29

    Like with indexed arrays, we can intialize a zero-length associative array and then add elements.

    Syntax $topics = array(); $topics ['tech1] = 'HTML'; $topics ['tech2'] = 'CSS'; $topics ['tech3'] = 'JavaScript'; $topics ['tech4'] = 'PHP';

    Or the array could be created in a single line as follows.

    Syntax

    $topics = array('tech1' => 'HTML',

    'tech2' => 'CSS', 'tech3' => 'JavaScript', 'tech4' => 'PHP'); Reading from Associative Arrays

    Reading from associative arrays is as simple as reading from indexed arrays.

    Syntax echo $topics['tech2']; //outputs CSS to the browser

    Looping through Associative Arrays

    The following code will loop through the entire $topics array outputting each element and its key to the browser.

    Syntax foreach ($topics $key => $topic) {

    echo "$key: $topic "; }

    foreach ($topics as $topic) {

    echo "$topic "; }

    The above code snippets are combined in the following example.

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 21 of 29

    Code Sample: AssociativeArrays.php

    Associative Arrays Associative Arrays

    Two-dimensional Arrays In PHP, two-dimensional arrays are arrays that

    contain arrays. You can think of the outer array as containing the rows and the inner arrays as containing the data cells in those rows. For example, a two-dimensional array called $Rockbands could contain the names of the bands and some of the songs that they sing. Below is a grid that represents such a two-dimensional array.

    Rockband Song1 Song2 Song3 Beatles Love Me Do Hey Jude Helter

    Skelter Rolling Stones

    Waiting on a Friend

    Angie Yesterday's Papers

    Eagles Life in the Fast Lane

    Hotel California

    Best of My Love

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 22 of 29

    The following code creates this two-dimensional array. The internal arrays are highlighted. Note that the header row is not included. Syntax

    $Rockbands = array( array('Beatles','Love Me Do', 'Hey Jude','Helter Skelter'), array('Rolling Stones','Waiting on a Friend','Angie', 'Yesterday\'s Papers'), array('Eagles','Life in the Fast Lane','Hotel California', 'Best of My Love'))

    Reading from Two-dimensional Arrays

    To read an element from a two-dimensional array, you must first identify the index of the "row" and then identify the index of the "column." For example, the song "Angie" is in row 1, column 2, (see footnote) so it is identified as $Rockbands[1][2].

    Looping through Two-dimensional Arrays

    To loop through a two-dimensional array, you need to nest one loop inside of another. The following code will create an HTML table from our two-dimensional array.

    Syntax The above code snippets are combined in the following example to output a Rockbands table.

    Code Sample: TwoDimensionalArrays.php

    Two-dimensional Arrays

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 23 of 29

    Two-Dimensional Arrays Rockband Song 1 Song 2 Song 3

    Finding the size of Multi-dimensional Arrays $plants = array('perennials' => array('Day Lilies', 'Coral Bells', 'Goldenrod', 'Russian Sage'), 'annuals' =>array('Begonia', 'Sweet Alyssum', 'Cosmos', 'Helioptrope')); // Recursive count echo "The number of elements: ", count($plants, COUNT_RECURSIVE),"\n";//output 10 echo "The number of arrays: ", count($plants), "\n"; // output 2

    Different Array initializing ways

    $fruits = array (

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 24 of 29

    "fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"), "numbers" => array(1, 2, 3, 4, 5, 6), "holes" => array("first", 5 => "second", "third")

    ); $array = array(1, 1, 1, 1, 1, 8 => 1, 4 => 1, 19, 3 => 13); $firstquarter = array(1 => 'January', 'February', 'March');//index starts from 1

    Array Sorting Functions Function What It Does array_multisort() Sorts multiple or multidimensional arrays arsort() Reverse sorts associative arrays alphabetically by value. The index

    association remains intact. asort() Sorts associative arrays alphabetically by value. The index

    association remains intact. krsort() Reverse sorts associative arrays alphabetically by key. The index

    association remains intact.

    ksort() Sorts associative arrays alphabetically by key. The index association remains intact.

    natcasesort() Sorts an array using a case--insensitive natural order algorithm natsort() Sorts an array using a natural order algorithm

    rsort() Sorts an array in reverse order shuffle() Shuffles an array

    sort() Sorts an array uasort() Sorts an array with a user--defined comparison function and

    maintains index association

    uksort() Sorts an array by keys using a user--defined comparison function usort() Sorts an array by values using a user--defined comparison function

    Sort Flags Flag What It Does SORT_LOCALE_STRING Compares items as strings, based on the current

    locale SORT_NUMERIC Compares items numerically SORT_REGULAR Compares items normally (does not change types) SORT_STRING Compares items as strings

    Alphabetic Sort $animals = array("dog", "cat", "horse", "monkey", "gorilla","zebra"); sort($animals);

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 25 of 29

    Numeric Sort $animals = array("5 dogs", "15 cats", "10 horses",

    "1 monkey", "1 gorilla", "2 zebras"); sort($animals, SORT_NUMERIC);

    Array Manipulation Functions The following table shows some of the more common array manipulation functions.

    Printing Arrays Function Explanation print_r() Displays both keys/indexes and values of an array Var_dump() Displays an arrays size, keys/indexes, values, and length

    Function Explanation array_count_values() Returns an array consisting of the values of an array and the

    number of times each value occurs in an array $hash_count = array_count_values( array("a","b", "a","a")); // Creates an associative array with "a" and "b" as the two keys and the number of times each occurs in the array (the associated value)

    array_fill(5, 6,php) Starting from 5 index, fill 6 values, all values php

    array_key_exists() Checks to see if a specified key exists in an array. array_keys() Returns all the keys of an associative array as an array.

    $array_of_keys = array_keys("apples", "pears", "peaches", "plums"); //Returns0,1,2,3 $array_of_keys = array_keys("Title"=>"King", "Name"=>"Barbar"); //Returns "Title", "Name"

    array_pad() Pads an array to the specified length with a value

    array_reverse() Returns an array with the elements in reverse order. array_values() returns an array with all the values of the original array

    $animals=array("tiger", "lion", "camel","elephant"); $array_of_values=array_values($animals); //Returns:"tiger","lion","camel","elephant"

    array_walk() Applies a user function to every element of an array.

    count() Returns the number of elements in an array. each() returns the current keyvalue pair in an array, and moves to the

    next element, making that the current element. The returned value is an array of two alternating values to represent each key and its corresponding value. To access the array elements, you can use either 0 and 1 to represent each key and value, or the keywords key and value to do the same thing. Used with a looping construct, each element of the array can be accessed until the array has reached its end. The reset() function sets the internal array pointer back to the beginning of the array if you want to access the array elements again. $colors=array('red','green', 'blue','yellow'); while($array = each($colors)) { // echo $array[0]." => " . $array[1]. ""; echo $array['key']." => " . $array['value']. "";

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 26 of 29

    }

    explode() Splits up a string by a specified delimiter and creates an array of strings $fruit = explode(" ", "apples pears peaches plums"); $fruit = explode("|", "apples|pears|peaches|plums",3);//creates a 3 element array

    implode() Creates a string by gluing together array elements by a specific separator $stats_array = array('name', 'ssn', 'phone'); $stats_string = implode(",", $stats_array);

    in_array() Checks if a value exists in an array is_array() Takes one parameter and returns true or false depending on whether

    the parameter passed is an array.

    join() Alias for implode()

    range(start, end, step)

    range(1, 5) // returns 1, 2, 3, 4, 5 range(1, 10, 2) //returns 1, 3, 5, 7, 9 range(15, 0, -5) //15, 10, 5, 0 range(-2, -8) //-2, -3, -4, -5, -6, -7, -8 range(a,c) //a, b, c

    rsort() Reverse sorts an array alphabetically. Elements will be assigned to new index numbers.

    shuffle() Randomly sorts the array. For the order to be sorted differently each time, the random number generator needs to be seeded with rsand(). $numbers = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); shuffle($numbers);

    sizeof() Returns the size of the array, same as count() sort() Sorts an array alphabetically. Elements will be assigned to new

    index numbers. split() Splits up a string into an array by a regular expression

    list() extracts elements from a numeric array (with index starting at 0) and assigns them to individual variables. Its arguments are a comma-separated list of variable names $swatch = array('blue', '#33A1C9', 'peacock'); list($color, $code, $name) = $swatch; // Create variables from array list($color, $code) = $swatch; // Ignore 'peacock' list($color, , $name)=$swatch; // Skip '#33A1C9'

    extract() creates variables from any associative array. The variables are named after the keys, and the values assigned to them are the same as the correspnding values in the associative array. $television = array("model"=>"Pan PX-44BBCCSTV","type"=>"plasma", "color"=>"charcoal bezel", "size"=>"42 in. widescreen"); extract($television);// Create variables from keys print " Model number after extract(): $model"; print "Values of variables created by extract():"; print "$model, $type, $color, $size";

    array_rand() The array_rand() function lets you select one or more random entries from an array. It takes an array as its argument and by default returns one random key or index value. If a second optional numeric argument is given, you can specify how many random keys to pick from the array, and an array of that number of random keys will be returned

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 27 of 29

    $colors=array("red","green","blue","yellow"); $random= array_rand($colors); // Returns a random color $random= array_rand($colors, 2); // Returns two random colors print $colors[$random[0]]; print $colors[$random[1]];

    Removing an Array and its Elements Function What It Does array_pop() Removes and returns the last element of an array array_shift() Removes and returns the first element of an array array_splice() Removes and/or replaces elements in an array array_unique() Removes duplicates from an array unset() Removes an entire array

    Adding Elements to an Array Function What It Does array_push() Pushes a new element(s) onto the end of the array array_splice() Removes and/or adds elements to an array at any

    position array_unshift() Adds a new element(s) to the beginning of the array

    Combining and Merging Arrays Function What It Does array_combine() returns an array made up of keys and values. The keys of the

    new array are made up of the values from the first array and the values associated with the new keys are made up of the values from the second array (PHP 5). The function returns FALSE if there are an unequal number of values in either of the arrays used as arguments.

    array_merge() joins two or more arrays together to return a single array. The values of one array are appended to the end of the previous array.

    Array Operators

    Operator Function Meaning $a + $b Union Union Of $a And $b $a == $b Equality TRUE If $a And $b Have the same keyvalue

    pairs $a === $b Identity TRUE If $a And $b Have the same keyvalue

    pairs in the same order and of the same types $a != $b Inequality TRUE If $a Is not equal to $b $a $b Inequality TRUE If $a Is not equal to $b $a !== $b Nonidentity TRUE if $a is not identical to $b

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 28 of 29

    Superglobal Arrays $_GET - variables passed into a page on the query

    string.

    $_POST - variables passed into a page through a form using the post method.

    $_SERVER - server environment variables (e.g, $_SERVER['HTTP_REFERER'] returns the URL of the referring page).

    $_COOKIE - cookie variables.

    $_FILES - variables containing information about uploaded files.

    $_ENV - PHP environment variables (e.g, $_ENV['HTTP_HOST'] returns the name of the host server. (see footnote)

    $_REQUEST - variables passed into a page through forms, the query string and cookies.

    $_SESSION - session variables.

    The PHP Superglobals are a handful of arrays that provide to a PHP script global access to data originating externally. Whereas PHP scripts contain variables that are local to that script and functions may have variables that are only accessible within that function, the PHP Superglobals represent data coming from URLs, HTML forms, cookies, sessions, and the Web server itself. $HTTP_GET_VARS, $HTTP_POST_VARS, etc., served these same purposes but the PHP superglobal variables are better in that they can also be accessed within any functions (i.e., they have global scope).

    $_GET The $_GET Superglobal represents data sent to the PHP script in a URL. This applies both to directly accessed URLs (e.g., http://www.example.com/page.php?id=2) and form submissions that use the GET method.

    $_POST The $_POST Superglobal represents data sent to the PHP script via HTTP POST. This is normally a form with a method of POST.

    $_COOKIE The $_COOKIE Superglobal represents data available to a PHP script via HTTP cookies.

    $_REQUEST The $_REQUEST Superglobal is a combination of $_GET, $_POST, and $_COOKIE.

    $_SESSION The $_SESSION Superglobal represents data available to a PHP script that has previously been stored in a session.

  • Web Application Development Using PHP-MySQL

    EVS Professional Training Institute http://www.evlearning.com/

    Page 29 of 29

    $_SERVER The $_SERVER Superglobal represents data available to a PHP script from the Web server itself. Common uses of $_SERVER is to refer to the current PHP script ($_SERVER['PHP_SELF']), the path on the server to that script, the host name, and so on.

    $_ENV The $_ENV Superglobal represents data available to a PHP script from the environment in which PHP is running.

    $_FILES The $_FILES Superglobal represents data available to a PHP script from HTTP POST file uploads. Using $_FILES is the currently preferred way to handle uploaded files in PHP.

    Another PHP Superglobal, called $GLOBALS, stores every variable with global scope, which includes the above. Unlike the other Superglobals, $GLOBALS has been around since PHP 3.

    Security Considerations One key aspect of Web application security is referring to variables with precision, which is why relying upon register_globals is bad. For the same reason, one should not use $_REQUEST as it is less exact, and therefore less secure, than explicitly referring to $_GET, $_POST, or $_COOKIE. Furthermore, the order in which the GET, POST, and COOKIE data is loaded into the $_REQUEST array is dictated by PHP's variables_orders configuration, so the same reference to $_REQUEST in a PHP script could behave differently on different servers.