630 likes | 758 Views
PHP - Hypertext Preprocessor . What is a PHP File?. PHP files may contain text, HTML tags and scripts PHP files are returned to the browser as plain HTML . Objectives. To learn to use several PHP functions useful for Web application development To learn to write and use your own functions.
E N D
What is a PHP File? PHP files may contain text, HTML tags and scripts PHP files are returned to the browser as plain HTML
Objectives To learn to use several PHP functions useful for Web application development To learn to write and use your own functions
Function A function is a block of code which can be called from any point in a script after it has been declared Contribute to rapid, reliable, error-reducing coding, and increase legibility
Type of Function • User-defined functions • Function arguments • Returning values • Variable functions • Anonymous functions
Function Some basic numeric PHP functions—E.g., i) absolute value[abs()], ii) square root [sqrt()], iii) round [round()], iv) integer checker[is_numeric()], v) random number generation [rand()] functions
The date function—We will discuss using the date() function to determine date and time information.
Functions • Function names in PHP are NOT case-sensitive. • Functions are defined using the keyword function. Example 1: function HelloMessage() // define a function without parameter { return "Hello World!"; // keyword “return” returns the result } echo HelloMessage(); // call the function; to execute it Output ? Lecture 6: Programming in PHP | SCK3633 Web Programming | Jumail FSKSM UTM 2012 | edited by Sarina Slide 9
Functions ….. Passing parameters by value function PrintValues($a, $b=10) { echo "a=$a, b=$b\n"; } PrintValues(5); PrintValues(5,15); Output ? default value Parameters that are set with a “default value” are optional when the function is called. Otherwise, they are compulsory. Lecture 6: Programming in PHP | SCK3633 Web Programming | Jumail FSKSM UTM 2012 | edited by Sarina Slide 10
You don’t need to use parenthesis with print() Double quotes means output the value of any variable: $x = 10; print ("Mom, please send $x dollars"); $x=5; print $x*3;
Single quotes means output the actual variable name $x = 10; print ('Mom, please send $x dollars'); Output = Mom, please send 10 dollars
What is an Array? A variable is a storage area holding a number or text. The problem is, a variable will hold only one value. An array is a special variable, which can store multiple values in one single variable. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: $cars1="Saab";$cars2="Volvo";$cars3="BMW";
An array can hold all your variable values under a single name. And you can access the values by referring to the array name. Each element in the array has its own index so that it can be easily accessed. In PHP, there are three kind of arrays: - Numeric array(An array with a numeric index) - Associative array(An array where each ID key is associated with a value) - Multidimensional array(An array containing one or more arrays)
Numeric Arrays A numeric array stores each array element with a numeric index.Thereare two methods to create a numeric array. 1. In the following example the index are automatically assigned (the index starts at 0): $cars=array("Saab","Volvo","BMW","Toyota"); 2. In the following example we assign the index manually: $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota";
The 2nd method use of the key / value structure of an array. The keys were the numbers we specified in the array and the values were the names of the cars. Each key of an array represents a value that we can manipulate and reference. The general form for setting the key of an array equal to a value is: $array[key] = value; If we wanted to reference the values that we stored into our array, the following PHP code would get the job done. Note: As you may have noticed from the above code example, an array's keys start from 0 and not 1. This is a very common problem for many new programmers who are used to counting from 1 and lead to "off by 1" errors. This is just something that will take experience before you are fully comfortable with it
Example In the following example you access the variable values by referring to the array name and index: The code above will output: Saab and Volvo are Swedish cars. <?php$cars[0]="Saab";$cars[1]="Volvo";$cars[2]="BMW";$cars[3]="Toyota"; echo $cars[0] . " and " . $cars[1] . " are Swedish cars.";?>
PHP array (Numeric) Numeric Arrays $names = array("Peter","Quagmire","Joe"); Assign manualy: • $names[0] = "Peter"; • $names[1] = "Quagmire"; • $names[2] = "Joe";
Associative Arrays • PHP also supports arrays with string-value indices called associative arrays. • An associative array, each ID key is associated with a value. • When storing data about specific named values, a numerical array is not always the best way to do it. • With associative arrays we can use the values as keys and assign values to them. • For example, the following code creates an associative array with three items. $instructor['Science'] = 'Smith'; $instructor['Math'] = 'Jones'; $instructor['English'] = 'Jackson';
Creating Associative Arrays Use the array() function along with the => operator to create an associative array.
Accessing Associative Array Items Use a syntax similar to sequential arrays to access items:
Example 1 In this example we use an array to assign ages to the different persons: $ages = array("Peter"=>32,"Quagmire"=>30, "Joe"=>34);
Example 2 • This example is the same as example 1, but shows a different way of creating the array: $ages['Peter'] = "32";$ages['Quagmire'] = "30";$ages['Joe'] = "34"; • The ID keys can be used in a script: <?php$ages['Peter'] = "32";$ages['Quagmire'] = "30";$ages['Joe'] = "34";echo "Peter is " . $ages['Peter'] . " years old.";?> • The code above will output: Peter is 32 years old.
Using foreach with associative arrays You can use foreach to access items from an associative array
Using foreach with associative arrays • Consider the following: $inventory = array('Nuts'=>33, 'Bolts'=>55, 'Screws'=>12); foreach ($inventory as $index => $item) { print "Index is $index, value is $item<br> "; } • The above outputs: Index is Nuts, value is 33 Index is Bolts, value is 55 Index is Screws, value is 12
Changing adding/deleting items • You can change an item by giving it a new value: $inventory = array('Nuts'=> 33, 'Bolts'=> 55, 'Screws'=> 12); $inventory['Nuts'] = 100; • You can add an item as follows: $inventory = array('Nuts'=>33, 'Bolts'=>55, 'Screws'=>12); $inventory['Nails'] = 23; • You can delete an item as follows: $inventory = array('Nuts'=> 33, 'Bolts'=>55, 'Screws'=>12); unset($inventory['Nuts']);
Verifying an items existance • You can use the isset() function to verify if an item exists. $inventory = array('Nuts'=> 33, 'Bolts'=>55, 'Screws'=> 12); if (isset($inventory['Nuts'])) { print ('Nuts are in the list.'); } else { print ('No Nuts in this list.'); }
Warning indices are case sensitive • Examine the following lines: $inventory = array( 'Nuts'=> 33, 'Bolts'=>55,'Screws'=>12 ); $inventory['nuts'] = 32; • Results in items 'Nuts', 'Bolts', 'Screws', and 'nuts'
Sorting Associative Arrays • You can sort associative arrays by values or indices. • Use asort() to sort by values: $dest = array('Dallas' => 803, 'Toronto' => 435, 'Boston' => 848, 'Nashville' => 406, 'Las Vegas' => 1526); asort($dest); foreach ($dest as $index => $value) { print " $index = $value "; } • The above would output: “Nashville = 406 Toronto = 435 Dallas = 803 Boston = 848 Las Vegas = 1526”.
Sorting Associative Arrays • Use ksort() to sort by indices: $dest = array ('Dallas' => 803, 'Toronto' => 435, 'Boston' => 848, 'Nashville' => 406,'Las Vegas' => 1526); ksort($dest); foreach ($dest as $index => $value) { print " $index = $value "; } • The above would output: “Boston = 848 Dallas = 803 Las Vegas = 1526 Nashville = 406 Toronto = 435”.
Multidimensional array Some data is best represented using a list of list or a multidimensional. For example:
In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Example : In this example we create a multidimensional array, with automatically assigned ID keys: • $families = array ( "Griffin"=>array ( "Peter", "Lois", "Megan" ), "Quagmire"=>array ( "Glenn" ), "Brown"=>array ( "Cleveland", "Loretta", "Junior" ) );
The array above would look like this if written to the output: Array([Griffin] => Array ( [0] => Peter [1] => Lois [2] => Megan )[Quagmire] => Array ( [0] => Glenn )[Brown] => Array ( [0] => Cleveland [1] => Loretta [2] => Junior ))
Creating Multidimensional Lists • You can create multidimensional arrays with the array() function $inventory['AC1000']['Part'] has the value Hammer, $inventory['AC1001']['Count'] has the value 5, and $inventory['AC1002']['Price'] has the value 10.00
http://mysite.com/login.php username=stud1&password=123 161.139.67.200 Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; NetCaptor 5.04) PHP Interpreter $_GET, $_POST, $_COOKIE, $_SERVER, etc. Environment Variable PHP interpreter converts the Web Server Environment Variables into hash arrays to make those variables easier to use. Web Server Web browser QUERY_STRING HTTP_REMOTE_ADDR HTTP_USER_AGENT Send URLs to web server Received information and stored in to variables called “CGI Environment Variables”.
Form Data $_GET: Contains form data that are sent using CGI method GET or data that supplied directly in the URL. $_POST: Contains form data that are sent using CGI method POST. URL: http://comp.fsksm.utm.my/~nometrik/myscript.php?a=5&b=10 $a=$_GET[“a”]; $b=$_GET[“b}; echo “a=$a, b=$b”; Output: a= 5, b=10
Function extract() Creating form data variables indirectly. Example: File: form.html File: myscript.php <form method="POST" name="form1" action="myscript.php"> Name: <input type="text" name="txtName"><br> Age: <input type="text" name="txtAge"><br> </form> extract($_POST); echo "Name: $txtName, Age: $txtAge";
Cookies Text file that stores in client’s computer by the Web site. (To maintain information about the client during and between browsing sessions. To record user preferences and other information that Web site can retrieve during the client’s subsequent visit.
Continue… Example: Store client’s zipcodes. Web site retrieve the zipcodes from the cookies and provide weather reports and news updates tailored to the user’s region. Web site use cookies to track information about client activity.
Continue… Cookies store on users hard drives: Raises issues regarding to privacy and security. Web sites should not store critical information to cookies as it is a text file that can read by anyone. Server can only access cookies that place on client. Cookies has expiration date, after which the web browser deletes it.
Continue… Cookies can be disable in the web browser: Disabling can make impossible for the user to interact with Web sites that rely on cookies to function properly. Information stored in the cookie is sent to the Web server from which it originated whenever the user requests a Web page from that particular server. The Web server can send the client HTML output that reflects the preferences or information that is stored in the cookie. Location of the cookie file varies from browser to browser.
$_COOKIE Contains all cookies that send by browser. Name of the cookie is the key. Cookie value becomes the array value.
Example: • PHP script is invoked from a client-side HTML document. • HTML document creates a form for the user to enter the information that will be stored in the cookie.
Form data is posted to cookies.php. cookie.html(page 2 of 2)