Introduction. Server-side Techniques. Introduction. 2 modes in the PHP processor:

Similar documents
Chapter 7:- PHP. Compiled By:- Sanjay Patel Assistant Professor, SVBIT.

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Chapter 11 Introduction to PHP

PHP INTERVIEW QUESTION-ANSWERS

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel

Programming for the Web with PHP

Database Systems Fundamentals

WEB APPLICATION ENGINEERING II

Hello everyone! Page 1. Your folder should look like this. To start with Run your XAMPP app and start your Apache and MySQL.

Mobile Site Development

Subject Name: Advanced Web Programming Subject Code: (13MCA43) 1. what is PHP? Discuss different control statements

Multimedia im Netz Online Multimedia Winter semester 2015/16. Tutorial 03 Minor Subject

You can also set the expiration time of the cookie in another way. It may be easier than using seconds.

Course Topics. The Three-Tier Architecture. Example 1: Airline reservations. IT360: Applied Database Systems. Introduction to PHP

Fachgebiet Technische Informatik, Joachim Zumbrägel

Tizen Ver2.2 - HTML5 Web Storage

Lecture 7: Dates/Times & Sessions. CS 383 Web Development II Wednesday, February 14, 2018

Lecture 12. PHP. cp476 PHP

Chapter 9. Managing State Information. Understanding State Information (continued) Understanding State Information 10/29/2011.

PIC 40A. Lecture 19: PHP Form handling, session variables and regular expressions. Copyright 2011 Jukka Virtanen UCLA 1 05/25/12

Persistence. SWE 432, Fall 2017 Design and Implementation of Software for the Web

CERTIFICATE IN WEB PROGRAMMING

Managing State. Chapter 13

Course Topics. IT360: Applied Database Systems. Introduction to PHP

Course Syllabus. Course Title. Who should attend? Course Description. PHP ( Level 1 (

Persistence & State. SWE 432, Fall 2016 Design and Implementation of Software for the Web

5/19/2015. Objectives. JavaScript, Sixth Edition. Saving State Information with Query Strings. Understanding State Information

Autopopulation; Session & Cookies

Web Programming 4) PHP and the Web

PHP with data handling

How browsers talk to servers. What does this do?

What is PHP? [1] Figure 1 [1]

CITS1231 Web Technologies. PHP s, Cookies and Session Control

Lecture 7b: HTTP. Feb. 24, Internet and Intranet Protocols and Applications

Computer Networks. Wenzhong Li. Nanjing University

B. V. Patel Institute of BMC & IT 2014

(Frequently Asked Questions)

DATABASE SYSTEMS. Introduction to web programming. Database Systems Course, 2016

CSE 154 LECTURE 21: COOKIES

CSE 154 LECTURE 21: COOKIES

PHP by Pearson Education, Inc. All Rights Reserved.

COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts

PHP Hypertext Preprocessor

Sessions. Mendel Rosenblum. CS142 Lecture Notes - Sessions

INSTITUTE OF AERONAUTICAL ENGINEERING (Autonomous) Dundigal, Hyderabad

Web Engineering (Lecture 08) WAMP

GET /index.php HTTP/1.1 Host: User- agent: Mozilla/4.0

Lecture 9a: Sessions and Cookies

Creating HTML files using Notepad

MCIS/UA. String Literals. String Literals. Here Documents The <<< operator (also known as heredoc) can be used to construct multi-line strings.

INTERNET ENGINEERING. HTTP Protocol. Sadegh Aliakbary

COMP519 Web Programming Lecture 28: PHP (Part 4) Handouts

CS6501 IP Unit IV Page 1

An Introduction to JavaScript & Bootstrap Basic concept used in responsive website development Form Validation Creating templates

Web, HTTP and Web Caching

Server-side computing

Unit 4 The Web. Computer Concepts Unit Contents. 4 Web Overview. 4 Section A: Web Basics. 4 Evolution

PHP 1. Introduction Temasek Polytechnic

PHP 5 Introduction. What You Should Already Know. What is PHP? What is a PHP File? What Can PHP Do? Why PHP?

magento_1:full_page_cache

URLs and web servers. Server side basics. URLs and web servers (cont.) URLs and web servers (cont.) Usually when you type a URL in your browser:

Dreamweaver MX The Basics

Excerpts of Web Application Security focusing on Data Validation. adapted for F.I.S.T. 2004, Frankfurt

The PHP language. Teaching you everything about PHP? Not exactly Goal: teach you how to interact with a database via web

Mount Saint Mary College, Newburgh, NY Internet Programming III - CIT310

CNIT 129S: Securing Web Applications. Ch 3: Web Application Technologies

PHP and MySQL for Dynamic Web Sites. Intro Ed Crowley

Web Scripting using PHP

Alpha College of Engineering and Technology. Question Bank

Static Webpage Development

Get in Touch Module 1 - Core PHP XHTML

Web development using PHP & MySQL with HTML5, CSS, JavaScript

Server side basics CS380

John Valance JValance Consulting

DevShala Technologies A-51, Sector 64 Noida, Uttar Pradesh PIN Contact us

USQ/CSC2406 Web Publishing

Document Management System GUI. v6.0 User Guide

magento_1:full_page_cache

WEB TECHNOLOGIES CHAPTER 1

Migration Tool. User Guide. SHOPIFY to MAGENTO. Copyright 2014 LitExtension.com. All Rights Reserved.

Web Programming with PHP

CPET 499/ITC 250 Web Systems. Topics

WEB SECURITY WORKSHOP TEXSAW Presented by Solomon Boyd and Jiayang Wang

WEB APPLICATION ENGINEERING II

COSC 2206 Internet Tools. The HTTP Protocol

Session 8. Reading and Reference. en.wikipedia.org/wiki/list_of_http_headers. en.wikipedia.org/wiki/http_status_codes

RKN 2015 Application Layer Short Summary

CSE 154 LECTURE 13: SESSIONS

Core PHP. PHP output mechanism. Introducing. Language basics. Installing & Configuring PHP. Introducing of PHP keywords. Operators & expressions

HTTP Reading: Section and COS 461: Computer Networks Spring 2013

COMS 469: Interactive Media II

CSCB20 Week 8. Introduction to Database and Web Application Programming. Anna Bretscher* Winter 2017

PHP: The Basics CISC 282. October 18, Approach Thus Far

HTML5 - INTERVIEW QUESTIONS

PHP. MIT 6.470, IAP 2010 Yafim Landa

Dreamweaver is a full-featured Web application

Web Programming TL 9. Tutorial. Exercise 1: String Manipulation

PHP State Maintenance (Cookies, Sessions, Hidden Inputs)

ONCONTACT MARKETING AND CAMPAIGN USER GUIDE V10

This FAQ is only applicable for hostings ordered after 23/6/2010

About the Authors. Who Should Read This Book. How This Book Is Organized

Transcription:

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