• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
 

Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)

on

  • 27,088 views

 

Statistics

Views

Total Views
27,088
Views on SlideShare
27,088
Embed Views
0

Actions

Likes
0
Downloads
46
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Can be used on characters too… (incrementing only, NOT decrementing) Follows Perl conventions… e.g. Code in initial.php : $i = "A"; $i++; echo $i; Output: B

Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23) Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23) Presentation Transcript

  • CLIENTWEB SERVERHTTP Request(url)<HTML><?php PHP code ?></HTML>Gets Page<HTML><B>Hello</B></HTML>Interprets the PHP codServer responseBrowser createsthe web pageHello
  • Server-Side Scripting A "skrip" adalah koleksi program atau urutanarahan yang ditafsirkan atau dijalankan olehprogram lain dan bukannya oleh pemproseskomputer. Server-side / Server-side Client-side / Pelanggan-side Dalam server-side scripting, (seperti PHP, ASP)skrip diproses oleh pelayan Like: Apache,ColdFusion, ISAPI dan Microsoft IIS padaWindows.
  • Server-Side Scripting – Continued Advantages of Server-Side Scripting Dynamic content. Computational capability. Database and file system access. Network access (from the server only). Built-in libraries and functions. Known platform for execution (as opposed toclient-side, where the platform is uncontrolled.) Security improvements
  • Introduction to PHP• PHP stands for PHP: HypertextPreprocessor• Developed by Rasmus Lerdorfin 1994• It is a powerful server-sidescripting language for creatingdynamic and interactivewebsites.• It is an open source software,which is widely used and free todownload and use (PHP isFREE to download from theofficial PHP resource:www.php.net).• It is an efficient alternative tocompetitors such as Microsofts• PHP adalah singkatan bagi PHP:Hypertext Preprocessor•Dibangunkan oleh Rasmus Lerdorf padatahun 1994•Ia adalah pelayan-side berkuasa bahasaskrip untuk mewujudkan laman webyang dinamik dan interaktif.•Ia merupakan perisian sumber terbuka,yang digunakan secara meluas danbebas untuk memuat turun danmenggunakan (PHP adalah PERCUMAuntuk memuat turun dari sumber rasmiPHP: www.php.net).•Ia merupakan alternatif yang berkesanuntuk pesaing seperti Microsoft ASP.
  • Introduction to PHP• PHP is perfectly suited for Webdevelopment and can beembedded directly into theHTML code.• The PHP syntax is very similarto JavaScript, Perl and C.• PHP is often used togetherwith Apache (web server) onvarious operating systems. Italso supports ISAPI and canbe used with Microsofts IIS onWindows.• PHP supports many databases(MySQL, Informix, Oracle,Sybase, Solid, PostgreSQL,Generic ODBC, etc.)• PHP adalah amat sesuai untukpembangunan web dan bolehditerapkan terus ke dalam kodHTML.•Syntax PHP adalah hampir samadengan JavaScript, Perl dan C.•PHP sering digunakan bersama-sama dengan Apache (webserver) dalam pelbagai sistemoperasi. Ia juga menyokong ISAPIdan boleh digunakan denganMicrosoft IIS pada Windows.•PHP menyokong banyakpangkalan data (MySQL, Informix,Oracle, Sybase, Pepejal,
  • Introduction to PHP• What is a PHPFile?• PHP files have a file extension of ".php",".php3", or ".phtml"• PHP files can contain text, HTML tags andscripts• PHP files are returned to the browser as plainHTML 
  • Introduction to PHPWhat you need to develop PHPApplication:• Install Apache (orIIS) on server, install PHP,and MySQL• OR• Install Wampserver2 (a bundle of PHP, Apache,and MySql server) on your own server/machine
  • PHP Installation DownloadsFree Download PHP: http://www.php.net/downloads.php MySQL Database: http://www.mysql.com/downloads/index.html Apache Server: http://httpd.apache.org/download.cgi• How to install and configure apache• Here is a link to a good tutorial from PHP.net on how to install PHP5:http://www.php.net/manual/en/install.php
  • How PHP is Processed• When a PHP document isrequested of a server, theserver will send the documentfirst to a PHP processor• Two modes of operation– Copy mode in which plainHTML is copied to the output– Interpret mode in whichPHP code is interpreted andthe output from that codesent to output– The client never sees PHPcode, only the outputproduced by the code• Apabila dokumen PHP dimintapelayan, pelayan akanmenghantar dokumen pertamadengan pemproses PHP.•Dua mod operasi:Mod salinan di mana HTMLbiasa disalin kepada output•Mod mentafsirdi mana kodPHP ditafsirkan dan outputdaripada kod yang dihantar keoutput•Pelanggan tidak pernah melihatkod PHP, hanya output yang
  • Basic PHPSyntax• PHP statements are terminated withsemicolons ;• Curly braces, { } are used to createcompound statements• Variables cannot be defined in acompound statement unless it is thebody of a function• PHP has typical scripting languagecharacteristics– Dynamic typing, un-typed variables– Associative arrays– Pattern matching– Extensive libraries• Primitives, Operations, Expressions– Four scalar types: boolean, integer,double, string– Two compound types: array, object– Two special types: resource and• Penyata PHP ditamatkan dengan komabertitik;•Pendakap kerinting, {} digunakan untukmembuat kenyataan kompaun•Pembolehubah tidak boleh ditakrifkan dalamsatu kenyataan kompaun melainkan jika iaadalah badan fungsi•PHP mempunyai ciri-ciri bahasa skrip yangbiasa- Menaip dinamik, pembolehubah un-ditaip- array bersekutu-pola yang sama-perpustakaan yang luasPrimitif, Operasi, Expressions-Empat jenis skalar: boolean, integer, double,tali
  • Basic PHPSyntax• A PHP scripting block always starts with <?php andends with ?><?php ……………. ?>– Other options are:1. <? ……………… ?>2. <script> ... </script>• There are three basic statements to output text withPHP: echo, print, and printf. Example:echo This is a <b>test</b>!;• Comments:– #– //– /* . . . * /
  • Basic PHPSyntax Inserting external files: PHP menyediakan empat fungsi yangmembolehkan anda untuk memasukkankod dari fail luaran : include() or require()include_once() or require_once()functions.• E.g. include("table2.php");– Includedfiles start incopymode
  • Basic PHPSyntaxExample 1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <title>Simple PHP Example</title><body><?phpecho "Hello Class of 2011. This is my first PHP Script";echo "<br />";print "<b><i>What have you learnt and how many friends have youmade?</i></b>";echo "<br /><a href=PHP I-BSIC.ppt>PHP BASIC</a>";?></body></html>
  • PHPVariables• Variables are used for storingvalues, such as numbers,strings or function results, sothat they can be used manytimes in a script.• All variables in PHP start with a$ sign symbol.• Variables are assigned usingthe assignment operator "="• Variable names are casesensitive in PHP: $name is notthe same as $NAME or $Name.• In PHP a variable does notneed to be declared beforebeing set.Example:<html><head><title>My first PHP page</title></head><body><?php$var1 = PHP; // Assigns a value of PHP to$var1$var2 = 5; // Assigns a value of 5 to $var2$var3 = $var2 + 1; // Assigns a value of 6 to$var3$var2 = $var1; // Assigns a value of PHP to $var2echo $var1; // Outputs PHP‘echo "<br/>";echo $var2; // Outputs PHPecho "<br/>";echo $var3; // Outputs 6echo "<br/>";echo $var1 . rules!; // Outputs PHP rules!echo "$var1 rules!"; // Outputs PHP rules!echo $var1 rules!; // Outputs $var1 rules!‘?></body>
  • Variable Naming Rules A variable name must start with a letter or anunderscore "_" A variable name can only contain alpha-numericcharacters and underscores (a-z, A-Z, 0-9, and _) If variable name is more than one word, it shouldbe separated with an underscore e.g.($my_string), or with capitalization ($myString)
  • Variable Scope and Lifetime The scope of a variabledefined within a functionis  local to that function. A variable defined in themain body of code has aglobal scope.  If a function needs to usea variable that is definedin the main body of theprogram, it must referenceit using the "global"• Example:<?phpfunction mul(){global $start;print "<tr>";for ($num=1; $num <= 10; $num++ ){$cell = $num * $start;print "<td> " . $cell . " </td>";}print "</tr>";}$start = 0;print "<table border=1cellpadding=3>";while ( $start <=10 ){mul();$start++;}print "</table>";?>
  • Strings in PHP• a string is a sequence of letters, symbols, characters and arithmetic values orcombination of all tied together in single or double quotes.• String literals are enclosed in single or double quotes• Example:<?php$sum = 20;echo the sum is: $sum;echo "<br />";echo "the sum is: $sum";echo "<br />";echo <input type="text" name="first_name" id="first_name">;?>– Double quoted strings have escape sequences (such as /n or /r) interpretedand variables interpolated (substituted)– Single quoted strings have neither escape sequence interpretation nor variableinterpolation– A literal $ sign in a double quoted string must be escaped with a backslash, – Double-quoted strings can cover multiple lines
  • Escaping quotes with in quotesExample 1:<?php$str = ""This is a PHP string examples quotes"";echo $str;?>Example 2<?php$str = Its a nice day today.;echo $str;?>
  • The Assignment Operator The Assignment operator is the most widely used and well known of all theoperators in PHP. You use it every time you create a variable. The"="(equal to) sign is used, and what it does is it takes the expression fromthe right and places it into the operand on the left. It is simple.In this example we use the assignment operator(=) to place a value of 8into the variable:<?php$var1 = 8;?>We can also combine operators together to produce expression results thatare set into our variables as value. We demonstrate this in the next fewlessons quite well. Let us continue on.
  • Some Types of Operator Arithmetic Assignment Bitwise Comparison Ternary• Incrementing/decrementing• Logical• String
  • String Operators Use a dot to concatenate two strings:e.g.$firstname = ‘Rob’;$surname = ‘Tuley’;// displays ‘Rob Tuley’echo $firstname.’ ‘.$surname;
  • Arithmetic OperatorsExample Name Result$a + $b Addition Sum of $a and $b.$a - $b Subtraction Difference of $a and $b.$a * $b Multiplication Product of $a and $b.$a / $b Division Quotient of $a and $b.$a % $b Modulus Remainder of $a divided by $b.
  • Assignment OperatorsExample Result$a = $b Sets $b to the same value as $a.$a += $b Equivalent to $a = $a + $b.$a .= $b Equivalent to $a = $a.$b.
  • Combining Operators Note that you can combine operators, forexample use =, + and / in one expression:$a = 4;$b = 2;$c = $a + $b + ($a/$b);// $c has value 4+2+(4/2) = 8 Brackets help group operators.
  • Comparison OperatorsExample Name Result$a == $b Equal TRUE if $a is equal to $b.$a != $b Not equal TRUE if $a is not equal to $b.$a <> $b Not equal TRUE if $a is not equal to $b.$a < $b Less than TRUE if $a is strictly less than $b.$a > $b Greater than TRUE if $a is strictly greater than $b.$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.$a >= $b Gtr than or equal to TRUE if $a is greater than or equal to $b.
  • Comparisons Comparison expressions return a value ofTRUE (or ‘1’) or FALSE (or ‘0’).e.g.$a = 10;$b = 13;// result is true (‘1’)echo $a < $b;
  • Incrementing/DecrementingExample Name Effect++$a Pre-increment Increments $a by one, then returns $a.$a++ Post-increment Returns $a, then increments $a by one.--$a Pre-decrement Decrements $a by one, then returns $a.$a-- Post-decrement Returns $a, then decrements $a by one.
  • Logical OperatorsExample Name Result$a and $b And TRUE if both $a and $b are TRUE.$a or $b Or TRUE if either $a or $b is TRUE.$a xor $b Xor TRUE if either $a or $b is TRUE, but not both.!$a Not TRUE if $a is not TRUE.$a && $b And TRUE if both $a and $b are TRUE.$a || $b Or TRUE if either $a or $b is TRUE.
  • Finally, a tricky one! A single ? is the ternary operator.(expr) ? if_expr_true : if_expr_false; A test expression evaluates to TRUE orFALSE. TRUE gives first result (before colon) FALSE gives second result (after colon)
  • Ternary Operator example<?php$a = 10;$b = 13;echo $a<$b ? ‘a smaller’:‘b smaller’;// string ‘a smaller’ is echoed// to the browser..?>
  • The Concatenation Operator• The concatenation operator (.)  is used to puttwo string values together.• Example:<?php$txt1="Hello Everyone,";$txt2="1234 is Dan’s home address";echo $txt1.$txt2;?>
  • Constants in PHP Constants are named values whose values cannot be changed. When you create aconstant you should use all capital letters and underscores separating words to letyourself and others know they are constants. A dollar sign is not needed in front ofthe name when creating constants. We use the define() function in PHP to createthem.Here is how we create a constant, and use true on the end to make it not worry aboutletter casing: Output:The person that created this web page is named Adam Khoury.<?php// define(constant_name, value, case_sensitive=true);define("AUTHOR_NAME", "Adam Khoury", true);echo "The person that created this web page is named " . AUTHOR_NAME . ".";?>
  • Control Structure Control structures are the building blocks ofany programming language. PHP provides allthe control structures that you may haveencountered anywhere. The syntax is thesame as C or Perl. Making computers think has always been thegoal of the computer architect and theprogrammer. Using control structurescomputers can make simple decisions andwhen programmed cleverly they can do somecomplex things.
  • Conditional Statements1. The If...ElseStatementSyntaxif (co nditio n) co de to bee xe cute d if co nditio n istrue ;else co de to be e xe cute d ifco nditio n is false ;<?php$d=date("D");if ($d=="Fri") echo "Have anice weekend!";If more than one line shouldbe executed if acondition is true/false,the lines should beenclosed within curlybraces:<?php$d=date("D");if ($d=="Fri"){ echo "Hello!<br />";echo "Have a niceweekend!";echo "See you on
  • Conditional Statements2.The ElseIf Statement• If you want to execute somecode if one of severalconditions is true use theelseif statementSyntaxif (co nditio n) co de to bee xe cute d if co nditio n istrue ;elseif (co nditio n) co de tobe e xe cute d if co nditio nis true ;<html><head> <title>good ......</title></head><body><?php$hour= date("H");if ($hour<= 11) {echo "good morning my friend"; }elseif ($hour> 11 && $hour< 18) {echo "good afternoon my friend"; }else { echo "good evening myfriend"; }?></body></html>
  • PHPSwitch Statement• If you want to select one of manyblocks of code to be executed, usethe Switch statement.• The switch statement is used toavoid long blocks of if..elseif..elsecode.Syntaxswitch (e xpre ssio n){case labe l1 : co de to be e xe cute d ife xpre ssio n = labe l1 ;break;case labe l2: co de to be e xe cute d ife xpre ssio n = labe l2;break;default: co de to be e xe cute d ife xpre ssio n is diffe re nt fro m bo thswitch ($textcolor){case "black":echo "Im black";break;case "blue":echo "Im blue";break;case "red":echo "Im red";break;default: // It must besomething elseecho "too bad!!, Imsomething else";}
  • PHPLooping• Looping statements in PHP are used toexecute the same block of code a specifiednumber of times.• In PHP we have the following loopingstatements:– while - loops through a block of code if and aslong as a specified condition is true– do...while - loops through a block of code once,and then repeats the loop as long as a specialcondition is true– for- loops through a block of code a specifiednumber of times– foreach - loops through a block of code for each
  • The while StatementSyntaxwhile (condition){// statements}Example<html> <head> <title>Let us count !!!</title></head><body><?php$limit = 10;echo "<h2> Let us count from 1 to $limit </h2><br />";$count = 1;while ($count <= $limit){echo "counting $count of $limit <br>";$count++;}?></body><html>
  • The do...while Statement• The do...whilestatement willexecute a block ofcode at least once -it then will repeat theloop as long as acondition is true.Syntax• do { co de to bee xe cute d; } while(co nditio n);Example<html> <body><?php$i=0;do { $i++; echo "The numberis " . $i . "<br />"; }while ($i<5);?></body> </html>
  • The forStatement• It is used when you know how manytimes you want to execute a statementor a list of statements.Syntax• for (init; co nd; incr) { co de to bee xe cute d; } Parameters:• init: Is mostly used to set a counter,but can be any code to be executedonce at the beginning of the loopstatement.• cond: Is evaluated at beginning ofeach loop iteration. If the conditionevaluates to TRUE, the loop continuesand the code executes. If it evaluatesto FALSE, the execution of the loopends.• incr: Is mostly used to increment aExample<html> <body><?phpfor ($i=1; $i<=5; $i++){echo "Hello World!<br />";}?></body> </html>
  • The foreach Statement• The foreach statement isused to loop through arrays.• For every loop, the value ofthe current array element isassigned to $value (and thearray pointer is moved byone) - so on the next loop,youll be looking at the nextelement.Syntax• foreach (array as value ){ co de to be e xe cute d; }Example<html> <body><?php$arr=array("one", "two","three");foreach ($arr as $value) {echo "Value: " . $value ."<br />";}?></body> </html>
  • Object and Classes in PHP PHP, like most modern programming languages (C++, Java, Perl, JavaScript, etc.),supports the creation of objects. Creating an object requires you to first define an object class (containing variablesand/or function definitions) and then using the “new” keyword to create an instance ofthe object class. (Note that the object must be defined before you instantiate it.)<?php// Assume that the "Person" object has been previously defined. . .$x = new Person; // creates an instance of the Person class (*no* quotes)// The object type need not be "hardcoded" into the declaration.$object_type = Person;$y = new $object_type; // equivalent to $y = new Person;$z = new Vehicle(Jaguar,green); // creating an object and passing// arguments to its constructor
  • Defining (declaring) a class Use the “class” keyword which includes the class name (case-insensitive, butotherwise following the rules for PHP identifiers). Note: The name “stdClass” isreserved for use by the PHP interpreter.<?phpclass Person{var $name;function set_name($new_name) {$name = $this -> new_name;}function get_name() {return $this -> name;}} Use the “$this” variable when accessing properties and functions of the currentobject. Inside a method this variable contains a reference to the object on whichthe method was called.
  • Declaring a class (cont.) Properties and functions can be declared as “public” (accessible outside theobject’s scope), “private” (accessible only by methods within the same class), or“protected” (accessible only through the class methods and the class methods ofclasses inheriting from the class. Note that unless a property is going to be explicitly declared as public, private, orprotected, it need not be declared before being used (like regular PHP variables).<?phpclass Person{protected $name;protected $age;function set_name($new_name) {$name = $this -> new_name;}function get_name() {return $this -> name;}}
  • Declaring a class (cont.) Classes can also have their own constants defined (using the “const” keyword), canhave their own static properties and functions (using the keyword “static” before“var” or “function”), and can also can constructors and destructors (see below). Static properties and functions are accessed (see below) using a different formatthan usual for objects, and static functions cannot access the objects properties(i.e. the variable $this is not defined inside of a static function).<?phpclass HTMLtable {static function start() {echo "<table> n";}static function end() {echo "</table> n";}}HTMLtable::start();?>
  • Accessing properties andmethods Once you have an object, you access methods and properties (variables) of theobject using the -> notation.<?php$me = new Person;$me -> set_name(Russ);$me -> print_name();$name = $me -> get_name();echo $me -> get_name();$age = 36;$me -> set_age($age);?>
  • PHP Function In php a function is a predefined set ofcommands that are carried out when thefunction is called. The real power of PHP comes from itsfunctions. PHP has more than 700 built-in or predefinefunctions for you to use. Complete php string reference You can write your own functions
  • Using Built-in Fuctions• Useful PHPStringFunctionsExample - strlen() Function<?php$str = "Hello world!";echo strlen($str);?>Example - strlen() Function<?php$str = “Hello world!”;echo strpos(“$str”,"world");?></body></html>• Useful PHPStringFunctions<?phpecho strlen("Helloworld!");echo "<br />";echo strpos("Helloworld!","world");?></body></html>
  • Using Built-in Function<html><head><title>My first PHP page</title></head><body><?php$a = abs(-.43);$b = sqrt(16);$c = round(12.3);print "The absolute value of -.43 is " . $a . "<br />";print "The square root of 16 is " . $b . "<br />";print "12.3 rounded is " . $c . " and 12.5 rounded is " . round(12.5);?></body></html>
  • Using Built-in Function Examples: Inserting external files: PHP provides four functions that enable you to insert codefrom external files: include() or require() include_once() orrequire_once() functions.A sample include file called add.php<html> <body><?phpfunction add( $x, $y ) {return $x + $y; }?><h1>Welcome to my home page</h1><p>Some text</p></body> </html>Using the include function<?phpinclude(add.php);echo add(2, 2); ?>
  • Using Built-in Function Inserting external files - continued: The functions are identical in every way, except how theyhandle errors. The include() and include_once() functions generates a warning (butthe script will continue execution) The require() and require_once() functions generates a fatal error(and the script execution will stop after the error). These functions are used to create functions, headers,footers, or elements that can be reused on multiple pages. This can save the developer a considerable amount of time forupdating/editing.
  •  Date Function Formatting DAYSd - day of the month 2 digits (01-31)j - day of the month (1-31)D - 3 letter day (Mon - Sun)l - full name of day (Monday - Sunday)N - 1=Monday, 2=Tuesday, etc (1-7)S - suffix for date (st, nd, rd)w - 0=Sunday, 1=Monday (0-6)z - day of the year (1=365) WEEKW - week of the year (1-52) MONTHF - Full name of month (January - December)m - 2 digit month number (01-12)n - month number (1-12)M - 3 letter month (Jan - Dec)t - Days in the month (28-31) YEARL - leap year (0 no, 1 yes)o - ISO-8601 year number (Ex. 1979, 2006)Y - four digit year (Ex. 1979, 2006)y - two digit year (Ex. 79, 06)• Date FunctionFormatting• TIMEa - am or pmA - AM or PMB - Swatch Internet time(000 - 999)g - 12 hour (1-12)G - 24 hour c (0-23)h - 2 digit 12 hour (01-12)H - 2 digit 24 hour (00-23)i - 2 digit minutes (00-59)s 0 2 digit seconds (00-59)• OTHERe - timezone (Ex:GMT, CST)I - daylight savings(1=yes, 0=no)O - offset GMT (Ex:0200)Z - offset in seconds (-43200 - 43200)
  • Using Built-in FunctionPHP Date() functionformatting characters:Example 1:<?php$theDate =date("m/d/y");echo "Todays dateis: $theDate";?>Example 2<?php$b = time ();print date("m/d/y",$b) . "<br />";print date("D, F jS",$b) . "<br />";print date("l, F jS Y",$b) . "<br />";print date("g:i A",$b) . "<br />";print date("r",$b) . "<br />";print date("g:i:s A D, F jS Y",$b) . "<br />";?>
  • Defining and Referencing aFunctionSyntaxfunction functionname () { your code }Example:<html> <body><?phpFunction Name(){echo "Ben John";}Name();?></body> </html>
  • PHPFunctions - Addingparameters A parameter is just like avariable. The parameters are specifiedinside the parentheses.Syntax:<?phpfunctionfunction_name(param_1,... , param_n){statement_1;statement_2;...statement_m;returnreturn_value;}?>Functions can also be used to returnvalues.Example:<html><body><?phpfunction add($x,$y){$total = $x + $y;return $total;}echo "1 + 16 = " . add(1,16);?></body></html>
  • PHPArrays An array can store one or more values in asingle variable name. There are three different kind of arrays: Numeric array - An array with a numeric ID key Associative array - An array where each ID key isassociated with a value Multidimensional array - An array containing oneor more arrays
  • Numeric Array• A numeric array stores each element witha numeric ID key.• There are different ways to create anumeric array:Example 1• In this example the ID key isautomatically assigned:• $names =array("Peter","Quagmire","Joe");Example 2• In this example we assign the ID keymanually:$names[0] = "Peter";$names[1] = "Quagmire";$names[2] = "Joe";Example 3:<?php$names[0] = "Peter";$names[1] = "Quagmire";$names[2] = "Joe";echo $names[1] . " and " .$names[2] . " are ".$names[0] . "sneighbors"; ?>
  • Associative Arrays• Each ID key is associated with avalue.• When storing data aboutspecific named values, anumerical array is not alwaysthe best way to do it.• There are two ways of creatingAssociative Array:Example 1• $ages = array("Peter"=>32,"Quagmire"=>30, "Joe"=>34);Example 2• $ages[Peter] = "32";$ages[Quagmire] = "30";$ages[Joe] = "34";Example 3:<?php$ages[Peter] = "32";$ages[Quagmire] = "30";$ages[Joe] = "34";echo "Peter is " .$ages[Peter] . " yearsold.";?>
  • Multidimensional Arrays• In a multidimensional array,each element in the mainarray can also be an array.And each element in thesub-array can be an array,and so on.• Example 1• with automatically assignedID keys:$families = array( "Griffin"=>array( "Peter", "Lois", "Megan" ),"Quagmire"=>array( "Glenn" ),"Brown"=>array( "Cleveland", "Loretta", "Junior")Example 2:The array above would look like this if written to theoutput:Array([Griffin] => Array([0] => Peter[1] => Lois[2] => Megan)[Quagmire] => Array([0] => Glenn)[Brown] => Array([0] => Cleveland[1] => Loretta[2] => Junior ))• displaying a single value from the arrayabove:echo "Is " . $families[Griffin][2] . " a part of theGriffin family?";
  • Strings Function Strlen Strstr Strpos Substr
  • Forms(Getting data from users)
  • Forms: how they work We need to know..1. How forms work.2. How to write forms in XHTML.3. How to access the data in PHP.
  • How forms workWeb ServerUserUser requests a particular URLXHTML Page supplied with FormUser fills in form and submits.Another URL is requested and theForm data is sent to this page either inURL or as a separate piece of data.XHTML Response
  • XHTML Form The form is enclosed in form tags..<form action=“path/to/submit/page”method=“get”><!–- form contents --></form>
  • Form tags action=“…” is the page that the form shouldsubmit its data to. method=“…” is the method by which the formdata is submitted. The option are either get orpost. If the method is get the data is passedin the url string, if the method is post it ispassed as a separate file.
  • Form fields: text input Use a text input within form tags for a singleline freeform text input.<label for=“fn">First Name</label><input type="text"name="firstname"id=“fn"size="20"/>
  • Form tags name=“…” is the name of the field. You willuse this name in PHP to access the data. id=“…” is label reference string – this shouldbe the same as that referenced in the<label> tag. size=“…” is the length of the displayed textbox (number of characters).
  • Form fields: password input Use a starred text input for passwords.<label for=“pw">Password</label><input type=“password"name=“passwd"id=“pw"size="20"/>
  • Form fields: text input If you need more than 1 line to enter data, usea textarea.<label for="desc">Description</label><textarea name=“description”id=“desc“rows=“10” cols=“30”>Default text goes here…</textarea>
  • Form fields: text area name=“…” is the name of the field. You willuse this name in PHP to access the data. id=“…” is label reference string – this shouldbe the same as that referenced in the<label> tag. rows=“…” cols=“..” is the size of thedisplayed text box.
  • Form fields: drop down<label for="tn">Where do you live?</label><select name="town" id="tn"><option value="swindon">Swindon</option><option value="london”selected="selected">London</option><option value=“bristol">Bristol</option></select>
  • Form fields: drop down name=“…” is the name of the field. id=“…” is label reference string. <option value=“…” is the actual data sentback to PHP if the option is selected. <option>…</option> is the valuedisplayed to the user. selected=“selected” this option isselected by default.
  • Form fields: radio buttons<input type="radio"name="age"id="u30“checked=“checked”value="Under30" /><label for="u30">Under 30</label><br /><input type="radio"name="age"id="thirty40"value="30to40" /><label for="thirty40">30 to 40</label>
  • Form fields: radio buttons name=“…” is the name of the field. All radioboxes with the same name are grouped withonly one selectable at a time. id=“…” is label reference string. value=“…” is the actual data sent back toPHP if the option is selected. checked=“checked” this option is selectedby default.
  • Form fields: check boxesWhat colours do you like?<br /><input type="checkbox"name="colour[]"id="r"checked="checked"value="red" /><label for="r">Red</label><br /><input type="checkbox"name="colour[]"id="b"value="blue" /><label for="b">Blue</label>
  • Form fields: check boxes name=“…” is the name of the field. Multiplecheckboxes can be selected, so if the button aregiven the same name, they will overwriteprevious values. The exception is if the name isgiven with square brackets – an array isreturned to PHP. id=“…” is label reference string. value=“…” is the actual data sent back toPHP if the option is selected. checked=“checked” this option is selectedby default.
  • Hidden Fields<input type="hidden"name="hidden_value"value="My Hidden Value" /> name=“…” is the name of the field. value=“…” is the actual data sent back toPHP.
  • Submit button.. A submit button for the form can be createdwith the code:<input type="submit"name="submit"value="Submit" />
  • Fieldset In XHTML 1.0, all inputs must be grouped within the form intofieldsets. These represent logical divisions through larger forms.For short forms, all inputs are contained in a single fieldset.<form><fieldset><input … /><input … /></fieldset><fieldset><input … /><input … /></fieldset></form>
  • In PHP… The form variables are available to PHP in thepage to which they have been submitted. The variables are available in two superglobalarrays created by PHP called $_POST and$_GET.
  • Access data Access submitted data in the relevant array forthe submission type, using the input name as akey.<form action=“path/to/submit/page”method=“get”><input type=“text” name=“email”></form>$email = $_GET[‘email’];
  • A warning..NEVER TRUST USER INPUT Always check what has been input. Validation can be undertaken using Regularexpressions or in-built PHP functions.
  • A useful tip.. I find that storing the validated data in adifferent array to the original useful. I often name this array ‘clean’ or somethingsimilarly intuitive. I then *only* work with the data in $clean, andnever refer to $_POST/$_GET again.
  • Example$clean = array();if (ctype_alnum($_POST[username])){$clean[username] = $_POST[username];}
  • Filter example$clean = array();if (ctype_alnum($_POST[username])){$clean[username] = $_POST[username];}$clean = array();Initialise an array to storefiltered data.
  • Filter example$clean = array();if (ctype_alnum($_POST[username])){$clean[username] = $_POST[username];}if (ctype_alnum($_POST[username]))Inspect username to makesure that it is alphanumeric.
  • Filter example$clean = array();if (ctype_alnum($_POST[username])){$clean[username] = $_POST[username];}$clean[username] = $_POST[username];If it is, store it in the array.
  • Is it submitted? We also need to check before accessing datato see if the data is submitted, use isset()function.if (isset($_POST[‘username’])) {// perform validation}
  • FORM Handling GET $_GET[name] POST $_POST[name] or just use the more general method $_REQUEST[‘name’]
  • FORM Example<form action="test.php" method="post"><table><tr><th>Name:</th><td><input type="text" name="name"></td></tr><tr><th>Age:</th><td><input type="text" name="age"></td></tr></table></form><p>Hello <?=$_POST[name]?>.You are <?=$_POST[age]?> years old.</p>
  • Example(a) A Web pagecontaining a form(b) A PHP script forhandling theoutput of the form(c) Output from thePHP script whenthe inputs are"Barbara" and 24respectively
  • The need for persistenceConsider these examples− Counting the number of “hits” on a website− i. e . how many times does a client load your web pagesource− The questionnaire on computing experienceSomehow your .php needs to remember previousinstances of it being requested by a client
  • PersistencePersistence is the ability of data to outlivethe execution of the program that createdthem.An obvious way of achieving persistence isto simply save the data in a file
  • Persistence and HTTPRecall http is a stateless protocol. It remembers nothing aboutprevious transfersTwo ways to achieve persistence:PHP cookiesPHP sessionsHTTPserverClientCookieSession
  • HTTP CookiesIn internet programming, a cookie is a packet of information sent from theserver to client, and then sent back to the server each time it is accessed by theclient.Introduces state into HTTP (remember: HTTP is stateless)Cookies are transferred between server and client according to http.PHP supports http cookiesCookies can also be thought of as tickets used to identify clients and theirorders
  • How Cookies are implementedCookies are sent from the server to the client via “Set-Cookie” headersSet-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secureThe NAME value is a URL-encoded name that identifiesthe cookie.The PATHand DOMAIN specify where the cookie applies
  • setcookie(name,value,expire,path,domain,secure)Parameter Descriptionname (Required). Specifies the name of the cookievalue (Required). Specifies the value of the cookieexpire (Optional). Specifies when the cookie expires.e.g. time()+3600*24*30 will set the cookie to expire in 30 days.If this parameter is not set, the cookie will expire at the end of the session (whenthe browser closes).path (Optional). Specifies the server path of the cookie.If set to "/", the cookie will be available within the entire domain.If set to "/phptest/", the cookie will only be available within the test directory andall sub-directories of phptest.The default value is the current directory that the cookie is being set in.domain (Optional). Specifies the domain name of the cookie.To make the cookie available on all subdomains of example.com then youd set itto ".example.com".Setting it to www.example.com will make the cookie only available in the wwwsubdomainsecure (Optional). Specifies whether or not the cookie should only be transmitted over asecure HTTPS connection.TRUE indicates that the cookie will only be set if a secure connection exists.Default is FALSE.
  • Cookies fromHTTPCookies fromHTTPGET /*.html HTTP/1.1Host: it026954.domainGET /*.html HTTP/1.1Host: it026945.domainCookie: name=valueAccept: */*HTTP/1.1 200 OKContent-type:text/htmlSet-Cookie:name=value(content of page)Client (e.g. Firefox) it026945
  • Creating PHPcookiesCreating PHPcookiesCookies can be set by directly manipulating the HTTP header usingthe PHP header() function<?phpheader(“Set-Cookie: mycookie=myvalue; path=/; domain=.coggeshall.org”);?>
  • Creating cookies withsetcookie()Use the PHP setcookie() function:Setcookie (name,value,expire, path, domain, secure)Setcookie (name,value,expire, path, domain, secure)e.g.<?phpsetcookie("MyCookie", $value, time()+3600*24);setcookie("AnotherCookie", $value, time()+3600);?>Name: name of the fileValue: data stored in the fileExpire: data string defining the life timePath: subset of URLs in a domain where it is validDomain: domain for which the cookie is validSecure: set to 1 to transmit in HTTPS
  • Reading cookiesReading cookies<?phpforeach ($_COOKIE as $key=>$val) {print $key . " => " . $val . "<br/>";}?>To access a cookie received from a client, use the PHP$_COOKIE$_COOKIE superglobal arrayEach key in the array represents a cookie - the key name isthe cookie name.
  • Creating and using cookiesCreating and using cookiesexampleexample<?phpsetcookie("MyCookie", $value, time()+7200);setcookie("AnotherCookie", $value, time()+7);?><?phpforeach ($_COOKIE as $key=>$val) {print $key . " => " . $val . "<br/>";}?>Cookies only become visible on the next page load
  • Using headers (wrongapproach!) <!DOCTYPE html PUBLIC "=//W3C//DTD XHMTL 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">   <html xmlns="http://www.w3.org/1999/xhmtl" xml:lang="en"> <head><title>PHP Script using Cookies</title> <meta http­equiv="Content­Type" content="text/html; chatset=ISO­8859­1" /> </head>   <body> <?php $strValue = "This is my first cookie"; setcookie ("mycookie", $strValue); echo "Cookie set<br>"; ?> </body>   </html>Gets an error!:Warning: Cannot modify header information - headers already sent by (output started at/var/www/html/TESTandre/159339/PHP/cookie_with_headers.php:9) in/var/www/html/TESTandre/159339/PHP/cookie_with_headers.php on line 11(adapted from Stobart & Parsons (2008))
  • Using headersUsing headers setcookie() did not run before informationwas sent to the browser... Cookies have to be sent beforetheheading elements
  • Using headers (correctapproach) <?php $strValue = "This is my first cookie"; setcookie ("mycookie", $strValue); echo "Cookie set<br>"; ?> <!DOCTYPE html PUBLIC "=//W3C//DTD XHMTL 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">   <html xmlns="http://www.w3.org/1999/xhmtl" xml:lang="en"> <head><title>PHP Script using Cookies</title> <meta http­equiv="Content­Type" content="text/html; charset=ISO­8859­1" /> </head>   <body>     <?php         echo “<p> A cookie has been set. </p>”;     ?>This is the correct approach!
  • Deleting a cookieSet the cookie with its name only:setcookie(“mycookie”);
  • Multiple data itemsUse explode() e.g.<?php$strAddress = $_SERVER[REMOTE_ADDR];$strBrowser = $_SERVER[HTTP_USER_AGENT];$strOperatingSystem = $_ENV[OS];$strInfo = "$strAddress::$strBrowser::$strOperatingSystem";setcookie ("somecookie4",$strInfo, time()+7200);?><?php$strReadCookie = $_COOKIE["somecookie4"];$arrListOfStrings = explode ("::", $strReadCookie);echo "<p>$strInfo</p>";echo "<p>Your IP address is: $arrListOfStrings[0] </p>";
  • Where is the cookie stored?
  • Where is the cookie storedDepends on the browser...e.g., firefox/mozilla under /home/a________− Look for cookies.txt in .mozilla directory− Usually under:/home/a______/.mozilla/firefox/asdkfljy.default− Cookie is stored only if there is an expiry date− Otherwise it is deleted when leaving browser− Persistent only if an e xpiry date is se t
  • You can store user information (e.g. username,items selected, etc.) in the serverside for lateruse using PHP session.SessionsSessions work by creating a unique id (UID) foreach visitor and storing variables based on thisUID.The UID is either stored in a cookie or ispropagated in the URL.PHPSessionsPHPSessions
  • When should you use sessions?When should you use sessions?Need for data to stored on the serverUnique session information for each userTransient data, only relevant for short timeData does not contain secret informationSimilar to Cookies, but it is stored on theserverMore secure, once established, no data is sentback and forth between the machinesWorks even if cookies are disabledExample: we want to count the number of“hits” on our web page.
  • <?php session_start(); ?><html><body></body></html>session_start() function must appear BEFORE the <html> tag.Before you can store user information in your PHPsession, you must first start up the session.
  • PHPSessionsPHPSessionsStarting a PHP session:<?phpsession_start();?>• This tells PHP that a session is requested.• A session ID is then allocated at the server end.• session ID looks like:sess_f1234781237468123768asjkhfa7891234g
  • Session variablesSession variables$_SESSIONe.g., $_SESSION[“intVar”] = 10;Testing if a session variable has been set:session_start();if(!$_SESSION[intVar]) {...} //intVar is set or not
  • Registering session variablesRegistering session variablesInstead of setting superglobals, one can register one’sown session variables<?php$barney = “A big purple dinosaur.”;$myvar_name = “barney”;session_register($myvar_name);?>• $barney can now be accessed “globally” from session tosessionThis only works if the register_globalsregister_globals directive is enabledin php.ini - nowadays this is turned off by defaultUse of session_register() is deprecated!
  • Make yourown session variablesMake yourown session variablesWith session_start()session_start() a default sessionvariable is created - the name extractedfrom the page nameTo create your own session variable justadd a new key to the $_SESSION$_SESSIONsuperglobal$_SESSION$_SESSION[‘dug’] = “a talking dog.”;Use of $_SESSION is preferred, as of PHP 4.1.0.
  • Session Example 1 <?php session_start(); if (!isset($_SESSION["intVar"]) ){ $_SESSION["intVar"] = 1; } else { $_SESSION["intVar"]++; } echo "<p>In this session you have accessed thispage " . $_SESSION["intVar"] . "times.</p>"; ?>
  • session_start();?>age = $_SERVER[PHP_SELF];ameArray = explode(/, $thisPage);ame = $pageNameArray[count($pageNameArray) ­ 1];"The name of this page is: $pageName<br/>";tems = explode(‘., $pageName);onName = $nameItems[0];"The session name is $sessionName<br/>";sset($_SESSION[$sessionName])) {$_SESSION[$sessionName] = 0;print "This is the first time you have visited this page<br/>"; $_SESSION[$sessionName]++;"<h1>You have visited this page " . $_SESSION[$sessionName] . times</h1>";Session Example 2Session Example 2
  • Ending sessionsunset($_SESSION[‘name’])–Remove a session variablesession_destroy()– Destroys all data registered to a session– does not unset session global variables and cookiesassociated with the session–Not normally done - leave to timeout
  • Destroying a sessioncompletely<?php// Initialize the session.// If you are using session_name("something"), dont forget it now!session_start();// Unset all of the session variables.$_SESSION = array();// If its desired to kill the session, also delete the session cookie.// Note: This will destroy the session, and not just the session data!if (ini_get("session.use_cookies")) { // Returns the value of the configuration option    $params = session_get_cookie_params();    setcookie(session_name(), , time() - 42000,        $params["path"], $params["domain"],        $params["secure"], $params["httponly"]    );}// Finally, destroy the session.session_destroy();?>http://nz2.php.net/manual/en/function.session-destroy.returns the name of thecurrent session
  • Session Example 3 <?php session_start(); if(!isset($_SESSION[strColourBg]))   $_SESSION[strColourBg] = "red"; else echo "Currently Bg set to " . $_SESSION[strColourBg] . "<br>"; if(!isset($_SESSION[strColourFg])) $_SESSION[strColourFg] = "yellow"; else echo "Currently Fg set to " . $_SESSION[strColourFg]; if(isset($_POST["submit"]) ) {   $strColourBg = $_POST["strNewBg"];   $strColourFg = $_POST["strNewFg"];   $_SESSION[strColourBg] = $strColourBg;   $_SESSION[strColourFg] = $strColourFg;   echo "<br>New Settings"; } else {   $strColourBg = $_SESSION[strColourBg];   $strColourFg = $_SESSION[strColourFg];   echo "<br>Keep old settings"; } ?>
  • Session Example 3 (cont.) <head> <style type="text/css">  body {background­color: <?php echo $strColourBg ?>} p {color: <?php echo $strColourFg?>} h2 {color: <?php echo $strColourFg?>} </style></head> <body> <h2>h2 colour</h2> <form action = <?php echo $SERVER["PHP_SELF"] ?> method=post> <label for="strNewBg"> Background colour: </label> <select name=strNewBg id=strNewBg>  <option>red</option> ...  <option>grey</option> </select> <label for="strNewFg"> Text colour: </label> <select name=strNewFg id=strNewFg>  <option>yellow</option> ... <option>grey</option> </select> <input type=submit name=submit/> </form></body> (adapted from Stobart & Parsons, 2008)
  • Examples php_imagefields.php php_retention.php upload.html upload.php php_imagefields.php php_imagecreation.php php_truetypefonts.php php_file_get_contents.php php_cookie_multipledata.php cookie1.php cookie_with_headers.phpsession1.phpsession2.phpphp_session_colours2.phpphp_session_destroy.php
  • SummaryPHP sessions and cookies are mechanismsfor introducing state into HTTPtransactions.