Introduction Server-side Techniques PHP Hypertext Processor A very popular server side language on web Code embedded directly into HTML documents http://hk2.php.net/downloads.php Features Free, open source Platform independent : implementations exist for UNIX, Linux, Windows Support for a large no of databases Excellent integration with Apache, mysql 1 2 Introduction 2 modes in the PHP processor: Copy (HTML) & interpret (PHP) When it finds HTML code in PHP document Copies it to the output file When it finds PHP script Interprets it and sends out HTML codes Output file: HTML codes only 3 4
Hello.php First PHP program <html> <head> <title> Hello </title> </head> <body> <?php echo "<h1> Hello from php </h1>"; echo "<p> Today is ". date("d/m/y"). "</p>";?> </body> </html> 5 6 user Request-Response (HTTP) Client (browser) URL: http://www.eie.polyu.e du.hk/hello.php Web Server GET hello.php HTTP/1.1 Host: www.eie.polyu.edu.hk HTTP/1.1 200 OK Find hello.php Parse the file Interpret php parts through PHP interpreter Produce HTML codes Client-side vs Server-side DHTML / JavaScript Sent from server to client Runs on the client Client is able to see those JavaScript codes PHP Runs on the server Client can see results only, not the PHP codes 7 8
Variables in PHP Variables: Always starts with $ Case-sensitive No need to be declared The type is set every time when it is assigned a value Multitype Can contain different types of data Integer $aninteger = 100; Double $adouble = 18.4; String $astring = Hello World ; php reserved words 9 10 Output 3 ywas to produce output echo echo info printing ; print print ( printing info! ); printf c syntax printf ( printing info! %d, $a); <?php Untyped $first = 10; $second=10.0; $third = "10"; Variables in PHP ==compared value === compared value and type if ($first == 10) print "One"; if ($second==10) print "Two"; if ($third == 10) print "Three"; if ($first === 10) print "Four"; if ($second===10) print "Five"; if ($third === 10) print "Six"; 11?> 12
Make a page with display like this: Example 4 <p> Select the month: <select name="month"> <option selected="selected" value=""> Please select </option> <?php for ($i=1; $i<=12; $i++) echo "<option value=\"$i\">$i</option>\n";?> </select> </p> code 13 14 Parameters Passing http://localhost/example5b/php?subject=maths Forms <form action= method= > Action: Specifies where the form data will be handled action= file1.php Form data will be sent to file1.php Method: 2 options: GET or POST code 15 16
Form Variables Form variables can be extracted from $_GET If the form data is submitted using the GET method url changes, depending on user s input $_POST If the form data is submitted using the POST method Data is sent in the body of the request string 17 Example 6 Examine differences between the GET and the POST methods Code: post Code: get 18 Example 7 <?php $in_fname = $_POST['firstname']; $in_email = $_POST['email']; $in_color = $_POST['color']; $in_lname = $_POST['lastname']; $in_telno = $_POST['phone']; Modify the previous form to include one more field: telephone no After the user clicks the submit button: with the use if-elseif-else statements, check the following: The entries in First name, Last name, email address and tel no: are not empty If either one is empty Display Please fill in all the information The entry in tel no is a numeric number (use is_numeric function) If it is not Display The telephone number is not a number All correct Display your information is now being processed?> <?php?> <?php?> <?php }?> if ( ) { <h3> your telephone number is not a number. Please try again. </h3> <p> <a href="ex5_form.html"> Back </a> </p> } else if ( ) { <h3> Your information is now being processed. </h3> } else { <h3> Please fill in all the information. </h3> <p> <a href="ex5_form.html"> Back </a> </p> Code: post 19 20
Example 8 Modify the previous page to include a text area for people to enter any text information. Find out the difference between trim($in_comment) nl2br(trim($in_comment)) $in_comment = $_POST['comment']; $in_comment1 = trim($in_comment); Code: post <textarea name="comment" rows="10" cols="20"> </textarea> solution 21 22 solution Arrays Arrays: Integer index: 0, 1, 2, $data = array( Year1, Year2, Year3"); Non-integer: $data = array( first => Year1, second => Year2, third => Year3 ); 23 24
Accessing Arrays C type: for ($i=0; $i< count($data); $i++) print ("element $i is $data[$i] <br /> "); Other methods: foreach($data2 as $value) print("$value <br />"); foreach($data2 as $key=>$value) print ("$key: $value <br />"); Function Example 10 Code 25 Code 26 Example11 Modify the programs in Example 10 so that the following display is obtained: A border is added to enclose the paragraph (note the spacing) Border color is specified by the user <head> <title> Form data from Post Method </title> <style type="text/css"> </style> <?php function processing($name, $email, $c) { print ("<p > $name, thank you for your message. <br />"); print (" We will "); }?> </head> Code 27 28
File Processing PHP: create, read and write files on server Basic types of processing Open a file $fp = fopen( filename.txt, r ); $fp = fopen( filename.txt, w ); Read from a file $data = fgets($file, [int length]) Reads the minimum of (one line or the no of bytes specified by length ) $data = file_get_contents(string $filename) Reads entire file into a string File Processing $fp = fopen(filename, indicator) indicator: r read only (from the beginning) r+ read & write, (from the beginning) w write only (from the beginning) w+ read & write (from the beginning) a write only (at the end) a+ read & write, read at the beginning write at the end 29 30 File Processing Basic types of processing Write to a file fwrite($fp, $outputstring); fwrite($fp, $outputstring, 5); Write the first five characters only Close the file fclose($fp); Use file_exists(filename) to determine where the file exists feof($fp): detect whether it is eof while(!feof($fp)) { } 31 Example 12 Code: php Code: txt 32
Maintaining Connection State Each HTTP request is unrelated to any other (from the point of view of web server) HTTP is stateless Common ways: Encode state information in the next URL to be used by the client State= abc Click the next button, url becomes?state=abc No good to send sensitive data Use cookie Use session What is Cookie? A chunk of text stored on a user s hard disk Give web browser a memory: scripts and server-side programs can use that data in another page Example uses: Store a user name and password Your script can enter these values stored in a cookie directly onto the login page Customize a page Use cookie to store personal settings, such as colors, layout, Track user visits Set up a simple counter that tracks the no of times a user has visited the page Bypass welcome messages, offer bonuses to frequent visitors, Create a shopping cart Use cookies to store the items and quantities ordered by the user 33 34 What is Cookie? Cookie: site-specific Your scripts can only read the cookies that have been created by pages on your site http://www.polyu.edu.hk/course/index.htm creates a cookie Cookie is visible to http://www.polyu.edu.hk/course/ex1.htm, http://www.polyu.edu.hk/course/eie/index.htm But not, http://www.polyu.edu.hk/index.htm Cookies might be rejected or turned off Cookies are browser-specific, computerspecific What is Cookie? Expiration date: If none given, cookie expires at the end of the session Security boolean Secure; or nothing Secure requires that the cookie should be used only if the connection is secure (e.g., HTTPS) 35 36
What is Cookie? Three steps: Server sends cookie to client (response header) What is Cookie? Set-Cookie: session=0x4137f; Expires=Wed, 09 Jun 2012 10:18:14 GMT Stored by the client-side web browser Client sends via an HTTP request Cookie: session=0x4137fd6a 37 38 Function: Cookie setcookie ("name", "value"); setcookie ("name", "value, expiration ); Expiration is in seconds 2 days = 60 x 60 x 24 x 2 12 hours = 60 x 60 x 12 Cookie1.php 39 40
ReadCookies.php Cookies Cookies must be created before any other HTML is created by the PHP Cookies stored in HTTP header User can disable cookies Intended for infrequent storage of small amounts of data Not intended as a general purpose communication or data-transfer mechanism Limitation: 4 kbytes of data per cookie, 20 cookies per web server 41 42 Sessions Sessions Alternative to cookies Keep track of the actions of a particular user over the period of time he/she is viewing your site Need: session identify number: a key that ties the user to his data Session variables: $_SESSION array 43 Session Handling: Method 1. Request to a page that starts a session 2. PHP generates a session ID and creates a file that stores the session-related variables 3. PHP: set a cookie to hold the session ID 44
Session Handling Specify the function at the top session_start() Initializes a session PHP will Check whether a valid session ID exists If not, PHP creates a new ID Note: PHP will set up a session cookie (PHPSESSID) Session variables: $_SESSION[ thevariable ] =. Example 45 46 Sessions session_destroy ( ) terminates a session Usually: wait for timeout Unset ($_SESSION[ thevariable ] ) Remove a particular session variable header() Redirection Sends a raw HTTP header header( Location: http://... ); Go to another page Refresh Refresh after a few seconds Header( refresh:5; url=login.html ); 47 48
Regular Expression describe patterns within text int preg_match (string pattern, string subject) Similar to the JavaScript s syntax ^: match at the start of a string $: match at the end of a string {n}: matches a pattern that has been repeated exactly n times {n, }: matches a pattern that has been repeated at least n times {n, m}: matches a pattern that has been repeated n to m times (inclusive) Regular Expression Similar to the JavaScript s syntax *: equivalent to {0, } +: equivalent to {1, }?: equivalent to {0,1} (): a group of patterns, e.g., (ab) : or operation, e.g., (a b).: any single character [0-9]: a digit [a-za-z]: a character (upper or lower case) 49 50 Useful Functions array preg_split (string pattern, string subject) Returns an array containing substrings of subject split along boundaries matched by pattern \s: a single whitespace character preg_split("/[\s,]+/","english, Chinese-traditional, Chinese-Simplified"); php 51 Useful Functions int preg_match (string pattern, string subject) Performs a regular expression match Stops at the first match int preg_match_all (string pattern, string subject, array matches) Returns a count of all matches matches[0]: an array of the full pattern matches php matches[1]: an array of sub-pattern 1 matches preg_match("/web/i", $astring, $match1) preg_match_all("/web/i", $astring, $match2) 52
Useful Functions preg_replace ($pattern, $replacement, $astring) Works for string and array preg_replace($pattern, $newpattern, $astring); php Test $string="hello World."; preg_match('/world/', $string) preg_match('/o W/', $string) preg_match('/ow/', $string) preg_match('/o/', $string) $string="hello+world."; preg_match('/o+w/', $string) preg_match('/o\+w/', $string) preg_match('/her/', $string) preg_match('/[her]/', $string) 53 54 Test $string="yes Yes yes yes YEs YeS"; preg_match('/[yy][ee][ss]/', $string) preg_match('/yes/', $string) preg_match('/yes/i', $string) Data Storage 55 56
Introduction Client-side cookies, sessions, HTML5 web storage Cookies: Info sent by a server to a browser, and then sent back by browser on future requests to same site All cookies set by server are sent to server during interaction Can be manipulated (i.e., stored as file on client) Can be persistent (set timeout) Introduction Sessions Stored on server Temporary and not permanent (deleted after user has left the website) HTML5 web storage localstorage, sessionstorage window.sessionstorage Values persist only as long as the window or tab in which they were stored Values are only visible within the window or tab that created them 57 58 Introduction HTML5 Local storage window.localstorage Values persist beyond window and browser lifetimes Values are shared across every window or tab running at the same origin php 59 60
HTML5 session storage HTML5 Web storage Removing data: localstorage.removeitem( no ) Clear all storage data: localstorage.clear() Get the number of pairs stored: localstorage.length php 61 62 Storage Domains and subdomains have different storage http://eie.polyu.edu.hk http://polyu.edu.hk Different sites on same domain have same storage http://eie.polyu.edu.hk/programme/index.html http://eie.polyu.edu.hk/activities/ac.html storage HTML5 web storage very much like cookies Differences: Cookies: 4 KB, localstorage: depends on browser (usually in MB) Unlike cookies, sessionstorage and localstorage data are NOT sent to server sessionstorage data confined to browser window that it was created in, lasts until browser is closed localstorage has longer persistent, can last even after browser is closed 63 64
Object Concept PHP: Object oriented programming Class: template Objects: instants Basic concept: Encapsulation Private variables var Inheritance (single) extends 65