Developing Web Applications with PHP - PowerPoint PPT Presentation

1 / 81
About This Presentation
Title:

Developing Web Applications with PHP

Description:

Developing Web Applications with PHP – PowerPoint PPT presentation

Number of Views:987
Avg rating:3.0/5.0
Slides: 82
Provided by: JeffJ97
Category:

less

Transcript and Presenter's Notes

Title: Developing Web Applications with PHP


1
Developing Web Applications with PHP
  • RAD for the World Wide Web

2
Introduction
  • Netcraft Statistics
  • 20,917,850 domains, 1,224,183 IP addresses

3
Programming Language Popularity
4
Introduction
  • What is PHP?
  • PHP stands for "PHP Hypertext Preprocessor
  • An embedded scripting language for HTML like ASP
    or JSP
  • A language that combines elements of Perl, C, and
    Java

5
Introduction
  • History of PHP
  • Created by Rasmus Lerdorf in 1995 for tracking
    access to his resume
  • Originally a set of Perl scripts known as the
    Personal Home Page tools
  • Rewritten in C with database functionality
  • Rewritten again in and released as version 2.0 in
    November of 1997

6
Introduction
  • History of PHP (cont.)
  • Rewritten again in 1997 by Andi Gutmans and Zeev
    Suraski OOP features
  • More functionality added, database support,
    protocols and APIs
  • The core is rewritten in 1998 by Zeev and Andi
    and dubbed the Zend Engine
  • Version 4.0 released in 2000

7
Introduction
  • History of PHP (cont.)
  • Version 5.0 includes version 2.0 of the Zend
    Engine
  • New object model is more powerful and intuitive
  • Objects are no longer passed by value they now
    are passed by reference
  • Increases performance and makes OOP more
    attractive

8
Introduction
  • Performance
  • Zdnet Statistics
  • PHP ? about 47 pages/second
  • Microsoft ASP ? about 43 pages/second
  • Allaire ColdFusion ? about 29 pages/second
  • Sun Java JSP ? about 13 pages/second From PHP
    HOWTO, July 2001

9
PHP Language Basics
  • The Script Tags
  • All PHP code is contained in one of several
    script tags
  • lt?// Some code?gt
  • lt?php// Some code here// This is the preferred
    method ?gt

10
PHP Language Basics
  • The Script Tags (cont.)
  • ltscript languagePHP"gt // Some code
    herelt/scriptgt
  • ASP-style tags
  • Introduced in 3.0 may be removed in the future
  • lt // Some code heregt

11
PHP Language Basics
  • The Script Tags (cont.)
  • Echo Tags
  • lttablegtlttrgt lttdgtNamelt/tdgtlttdgtlt? name
    ?gtlt/tdgtlt/trgtlttrgt lttdgtAddresslt/tdgtlttdgtlt?
    address ?gtlt/tdgtlt/trgtlt/tablegt

12
PHP Language Basics
  • Hello World! An Example
  • Like Perl, there is more than one way
  • lt?php echo Hello World! ?gt
  • lt?php greeting Hello World!
    printf(s, greeting)php?gt
  • ltscript languagePHPgt hello Hello
    world World! print hello .
    worldlt/scriptgt

13
PHP Language Elements
  • Variables
  • start with followed by name
  • name must start with _ or alphabetic
  • name can contain _ or alphanumeric
  • Operators
  • Arithmetic - /
  • Assignment -
  • Bitwise \ ltlt gtgt
  • Comparison ! lt gt lt gt
  • Logical and or xor !

14
PHP Language Basics
  • Constants, Data Types and Variables
  • Constants define a string or numeric value
  • Constants do not begin with a dollar sign
  • Examples
  • define(COMPANY, Acme Enterprises)
  • define(YELLOW, FFFF00)
  • define(PI, 3.14)
  • define(NL, ltbrgt\n)
  • Using a constant
  • print(Company name . COMPANY . NL)

15
PHP Language Basics
  • Constants, Data Types and Variables
  • Data types
  • Integers, doubles and strings
  • isValid true // Boolean
  • 25 // Integer
  • 3.14 // Double
  • Four // String
  • Total value // Another string

16
PHP Language Basics
  • Constants, Data Types and Variables
  • Data types
  • Strings and type conversion
  • street 123
  • street street . Main Street
  • city Napervillestate IL
  • address street
  • address address . NL . city, state
  • number address 1 // number equals
    124

17
PHP Language Basics
  • Constants, Data Types and Variables
  • Data types
  • Arrays
  • Perl-like syntax for hashes
  • arr array("foo" gt "bar", 12 gt true)
  • same as
  • arrfoo bar
  • arr12 true

18
PHP Language Basics
  • Constants, Data Types and Variables
  • Arrays (cont.)
  • lt?php arr array("somearray" gt array(6 gt
    5, 13 gt 9, "a" gt
    42)) echo arr"somearray"6 // 5
    echo arr"somearray"13 // 9 echo
    arr"somearray""a" // 42?gt

19
PHP Language Elements
  • Statements
  • terminated by a semicolon () or the closing PHP
    tag.
  • compound statements enclosed in braces
  • Comments
  • C / / , C //.. and shell style
  • Types
  • array, boolean, floating-point, integer, string,
    object
  • arrays behave as hash tables
  • var1 36.7 varmy name Marianne Brown
  • key needs to be either an integer or string
  • value can be anything

20
PHP Control Structures
  • if-then-else
  • if (expr)
  • stmt
  • elseif (expr)
  • stmt
  • else
  • stmt

21
PHP Control Structures
  • while loop
  • while (expr)
  • stmt
  • do-while loop
  • do
  • stmt
  • while (expr)

22
PHP Control Structures
  • for loop
  • for (expr1 expr2 expr3)
  • stmt
  • switch statement
  • switch (expr)
  • case 0 stmt
  • break
  • case 1
  • case 2 stmt
  • break
  • default stmt

23
PHP Functions
  • The function keyword declares a function.
  • function square(num)
  • return num num
  • echo square(4) // outputs 16

24
Functions
function add(a, b) return a
b function swap(a, b) c a a
b b a count 0 function inc()
global count count
25
PHP Functions
  • header() send http header to client
  • setcookie() send cookie to client
  • mail() send email from php
  • dns_get_mx() check mail exchange record
  • connection_status() check connection status,
    e.g. abort, timeout
  • gethostbyname() get IP address of host
  • ftp functions ftp_connect(), ftp_login(),
    ftp_fget(), ftp_fput(),

26
PHP Classes
  • class Cart
  • var todays_date
  • var name
  • var owner
  • function Cart()
  • this-gttodays_date date(Y-m-d)
  • function addItem(code, descript, qty)
  • / stuff /
  • cart new Cart
  • cart-gtaddItem(002564,1kg Tin Beans, 10)

27
FORM Handling
  • GET
  • _GET'name'
  • POST
  • _POST'name'
  • or just use the more general method
  • _REQUESTname

28
FORM Example
ltform action"test.php" method"post"gt lttablegt
lttrgt ltthgtNamelt/thgt lttdgtltinput
type"text" name"name"gtlt/tdgt lt/trgt lttrgt
ltthgtAgelt/thgt lttdgtltinput type"text"
name"age"gtlt/tdgt lt/trgt lt/tablegt lt/formgt
ltpgtHello lt?_POST'name'?gt. You are
lt?_POST'age'?gt years old.lt/pgt
29
Session
  • Start session - session_start()
  • Need to call before output
  • If session has started already, load registered
    session variables. Otherwise, create a new
    session.
  • Uses cookies to identify session (PHPSESSID)
  • Session variables stored on server
  • _SESSIONname value
  • isset(_SESSIONname)
  • session_destroy()

30
PHP Include
  • Universal header and footer
  • Create a file called header.php. This file will
    have all of theheader HTML code. You can use
    FrontPage/Dreamweaver to create the header, but
    remember to remove the closing lt/BODYgt and
    lt/HTMLgt tags.

31
PHP Include
  • Universal header and footer
  • Next, create a file called footer.php. This file
    will have all of the footer HTML code.

32
PHP Include
  • Universal header and footer
  • This is the basic template that you will use on
    all of the pages. Make sure you name the files
    with a .php extension so that the server will
    process the PHP code. In this example, we assume
    the header and footer files are located in the
    same directory.

33
Built-in Functions
  • What comes In the box?
  • Array Manipulator Functions
  • sort, merge, push, pop, slice, splice, keys,
    count
  • keysarray array_keys(somearray)
  • asort(somearray) // sorts - preserves
    associations
  • String Manipulation Functions
  • Strlen, trim, substr, ucfirst, ucwords,
    strtolower, strtoupper, strstr, strcasecmp,
    strtok, str_replace,
  • explode, implode, join - array/string
    transformations
  • Date and Time Functions
  • getdate, mkdate, date, gettimeofday, localtime,
    strtotime, time

34
Built-in Functions
  • What comes In the box?
  • Directory Functions
  • Platform independent
  • Error Handling Functions
  • Recover from warnings and errors
  • Filesystem Functions
  • Access flat files
  • Check directory, link, and file status
    information
  • Copy, delete, and rename files

35
Built-in Functions
  • Regular Expressions
  • Regular expression syntax identical to PERL
  • Functions
  • preg_match(pattern, string, matches)
  • preg_match_all(pattern, string)
  • preg_replace(pattern, replacement, string)
  • array preg_split(pattern, string)

36
Regex Example
lthtmlgt ltheadgtlttitlegtRegex in PHPlt/titlegtlt/headgt ltb
odygt lth1gtUsing Regex in PHPlt/h1gt lt?php test
"cookiesmultipackchocolatebrownies" parts
preg_split("//", test) echo "ltulgt" while
(list(key, val) each(parts)) echo
"ltligtkey vallt/ligt" echo "lt/ulgt" ?gt lt/bod
ygt lt/htmlgt
37
Built-in Functions
  • What comes In the box?
  • IMAP Functions
  • Manipulate mail boxes via the IMAP protocol
  • LDAP Functions
  • Works with most LDAP servers
  • Mail Functions
  • mail(recipient, subject, message)
  • CCVS Interface to Red Hats credit system

38
Built-in Functions
  • What comes In the box?
  • Database Functions
  • dba dbm-style abstraction layer
  • dBase
  • Frontbase
  • Informix
  • Ingres II
  • Interbase
  • mSQL

39
Built-in Functions
  • What comes In the box?
  • Database Functions (cont.)
  • MySQL
  • Oracle
  • PostgreSQL
  • SQL Server
  • MING
  • Macromedia Flash
  • PDF
  • Create/manipulate PDF files dynamically

40
lt?php class DAO private link private
db public function __construct(host,
dbname) link mysql_connect(host
) db mysql_select_db(dbname,
link) if (!db)
die("Unable to connect to database\n")
public function getPeople()
query "select from QuinnsTable"
if (result mysql_query(query))
i 0 while (data
mysql_fetch_object(result))
peoplei data
i return people
else //
Check result. This shows the actual query sent to
MySQL, and the error. Useful for debugging.
message 'Invalid query ' .
mysql_error() . "\n . 'Whole query ' . query
die(message) ?gt
41
Built-in Functions
  • What comes In the box?
  • POSIX Functions
  • Manipulate process information
  • Semaphore and Socket Functions
  • Available only on Unix
  • Session Management Functions

42
Numeric Value Validation
  • All data passed to PHP (GET/POST/COOKIE) ends up
    being a string. Using strings where integers are
    needed is not only inefficient but also dangerous.
  • // integer validation
  • if (!empty(_GET'id'))
  • id (int) _GET'id'
  • else
  • id 0
  • // floating point number validation
  • if (!empty(_GET'price'))
  • price (float) _GET'price'
  • else
  • price 0
  • Casting is a simple and very efficient way to
    ensure variables do in fact contain numeric
    values.

43
Validating Strings
  • PHP comes with a ctype, extension that offers a
    very quick mechanism for validating string
    content.
  • if (!ctype_alnum(_GET'login'))
  • echo "Only A-Za-z0-9 are allowed."
  • if (!ctype_alpha(_GET'captcha'))
  • echo "Only A-Za-z are allowed."
  • if (!ctype_xdigit(_GET'color'))
  • echo "Only hexadecimal values are
    allowed"

44
Path Validation
  • Values passed to PHP applications are often used
    to specify what file to open. This too needs to
    be validated to prevent arbitrary file access.
  • http//example.com/script.php?path../../etc/passw
    d
  • lt?php
  • fp fopen(/home/dir/_GETpath, r)
  • ?gt

45
Path Validation
  • PHP includes a basename() function that will
    process a path and remove everything other than
    the last component of the path, usually a file
    name.
  • lt?php
  • _GETpath basename(_GETpath)
  • // only open a file if it exists.
  • if (file_exists(/home/dir/_GETpath))
  • fp fopen(/home/dir/_GETpath, r)
  • ?gt

46
XSS
  • Cross Site Scripting (XSS) is a situation where
    an attacker injects HTML code, which is then
    displayed on the page without further validation.
  • Can lead to embarrassment.
  • Session take-over.
  • Password theft.
  • User tracking by 3rd parties.

47
Preventing XSS
  • Prevention of XSS can be as simple as filtering
    input data via one of the following
  • htmlspecialchars()
  • Encodes , , lt, gt,
  • htmlentities()
  • Convert anything that there is HTML entity for.
  • strip_tags()
  • Strips anything that resembles HTML tag.

48
Preventing XSS
  • str strip_tags(_POST'message')
  • // encode any foreign special chars
  • str htmlentities(str)
  • // maintain new lines, by converting them to ltbr
    /gt
  • echo nl2br(str)
  • // strip tags can be told to "keep" certain tags
  • str strip_tags(_POST'message',
    'ltbgtltpgtltigtltugt')
  • str htmlentities(str)
  • echo nl2br(str)
  • Tag allowances in strip_tags() are dangerous,
    because attributes of those tags are not being
    validated in any way.

49
Tag Allowance Problems
  • ltb style"font-size 500px"gt
  • TAKE UP ENTIRE SCREEN
  • lt/bgt
  • ltu onmouseover"alert('JavaScript is allowed')"gt
  • ltb style"font-size 500px"gtLot's of textlt/bgt
  • lt/ugt
  • ltp style"background url(http//tracker.com/image
    .gif)"gt
  • Let's track users
  • lt/pgt

50
Error Reporting
  • By default PHP will print all errors to screen,
    startling your users and in some cases disclosing
    privileged information.
  • File paths.
  • Un-initialized variables.
  • Sensitive function arguments such as passwords.
  • At the same time, disabling error reporting would
    make bug tracking near impossible.

51
Solution?
  • This problem can be solved by disabling
    displaying of error messages to screen
  • ini_set(display_errors, FALSE)
  • And enabling logging of errors
  • ini_set(log_errors, TRUE)
  • to a file
  • ini_set(error_log, /var/log/php.log)
  • or to system central error tracking facility
  • ini_set(error_log, syslog)

52
Session Security
  • Sessions are a common tool for user tracking
    across a web site.
  • For the duration of a visit, the session is
    effectively the users identity.
  • If an active session can be obtained by 3rd
    party, it can assume the identify of the user
    whos session was compromised.

53
Securing Session ID
  • To prevent session id theft, the id can be
    altered on every request, invalidating old values.
  • lt?php
  • session_start()
  • if (!empty(_SESSION)) // not a new session
  • session_regenerate_id(TRUE) // make new session
    id
  • ?gt
  • Because the session changes on every request, the
    back button in a browser will no longer work,
    as it will make a request with the old session id.

54
Session Validation
  • Another session security technique is to compare
    the browser signature headers.
  • session_start()
  • chk _at_md5(
  • _SERVER'HTTP_ACCEPT_CHARSET' .
  • _SERVER'HTTP_ACCEPT_ENCODING' .
  • _SERVER'HTTP_ACCEPT_LANGUAGE' .
  • _SERVER'HTTP_USER_AGENT')
  • if (empty(_SESSION))
  • _SESSION'key' chk
  • else if (_SESSION'key' ! chk)
  • session_destroy()

55
PHP MVC
  • PHP doesnt quite provide all that we really want
    to implement a MVC
  • You would like to forward the user to a
    particular view cant
  • We can include a particular view as needed

56
PHP MVC
57
index.php
lt?php // All interaction goes through the index
and is forwarded // directly to the
controller include_once("controller/Controller.ph
p") controller new Controller() controller-
gtinvoke() ?gt
58
model/Book.php
lt?php class Book public title public
author public description public
function __construct(title, author,
description) this-gttitle
title this-gtauthor author
this-gtdescription description ?gt
59
model/Model.php
lt?php include_once("model/Book.php") class
Model public function getBookList()
// here goes some hardcoded values to
simulate the database return array(
"Jungle Book" gt new Book("Jungle Book",
"R. Kipling", "A classic book."),
"Moonwalker" gt new Book("Moonwalker", "J.
Walker", ""), "PHP for Dummies" gt
new Book("PHP for Dummies", "Some Smart Guy",
"") ) public function
getBook(title) // we use the
previous function to get all the books
// and then we return the requested one.
// in a real life scenario this will be done
through // a database select command
allBooks this-gtgetBookList()
return allBookstitle ?gt
60
view/viewbook.php
lthtmlgt ltheadgtlt/headgt ltbodygt lt?php
echo 'Title' . book-gttitle . 'ltbr/gt'
echo 'Author' . book-gtauthor . 'ltbr/gt'
echo 'Description' . book-gtdescription .
'ltbr/gt' ?gt lt/bodygt lt/htmlgt
61
view/booklist.php
lthtmlgt ltheadgtlt/headgt ltbodygt lttablegt
lttbodygt lttrgtlttdgtTitlelt/tdgtlttdgtAuthorlt/td
gtlttdgtDescriptionlt/tdgtlt/trgt lt/tbodygt
lt?php foreach (books as book)
echo
'lttrgtlttdgtlta href"index.php?book' .
book-gttitle . '"gt' . book-gttitle .
'lt/agtlt/tdgtlttdgt' .
book-gtauthor . 'lt/tdgtlttdgt' . book-gtdescription
. 'lt/tdgtlt/trgt' ?gt
lt/tablegt lt/bodygt lt/htmlgt
62
controller/Controller.php
lt?php include_once("model/Model.php") class
Controller public model public
function __construct()
this-gtmodel new Model()
63
controller/Controller.php
public function invoke() if
(!isset(_GET'book'))
// no special book is requested, we'll show a
list of all available books books
this-gtmodel-gtgetBookList()
include 'view/booklist.php'
else // show the
requested book book
this-gtmodel-gtgetBook(_GET'book')
include 'view/viewbook.php'
?gt
64
PHP MVC
65
Another Example
  • Forward information from one page to the next as
    a user fills out a multi-part form.
  • Model
  • Lives in _SESSION
  • Views
  • Contain the forms
  • Controller
  • Adds data to the model as it comes in and
    includes the appropriate view

66
lt?php // Note that there is no html in this and
no printing class Controller public
function invoke() session_start()
if(_REQUEST'name')
_SESSION'name' _REQUEST'name'
if(_REQUEST'address')
_SESSION'address' _REQUEST'address'
switch (_SESSION'lastpage')
case '1' include
('View2.php') break
case '2' include ('View3.php')
break default
include ('View1.php')
?gt
67
lt?php session_start() _SESSION'lastpage'
'1' include("header.php") ?gt lth1gtView
1lt/h1gt ltform actionindex.php"
method"POST"gt Please enter your name ltinput
type"text" name"name"gt ltinput type"submit"
value"Submit"gt lt?php include("footer.php") ?gt
68
Tricks and Tips
  • Coding
  • Prototype your web pages first
  • Separate the design of the site from the coding
  • Turn repetitive code into functions
  • Makes for more maintainable and reusable code
  • Turn grunt code into functions
  • Database access, configuration file access

69
Tricks and Tips
  • Debugging
  • Feature PHP is not a strongly typed language
  • Variables can be created anywhere in your code
  • Undocumented Feature PHP is not a strongly typed
    language
  • Typos in variable names will cause stuff to happen

70
Tricks and Tips
  • Debugging
  • Use scripts to dump form and session variables
  • Write scripts to dump data to discover bad or
    missing data

71
PHP 5
  • Features
  • Complete objects
  • Objects with constructors
  • Abstract classes
  • Private, protected and abstract functions
  • Private, protected and constant variables
  • Namespaces
  • Exception handling with try/catch blocks

72
Additional Information
  • Some of the new functions added in version 5
  • Arraysarray_combine() - Creates an array by
    using one array for keys and another for its
    values
  • array_walk_recursive() - Apply a user function
    recursively to every member of an array
  • Date and Time Related
  • idate() - Format a local time/date as integer
  • date_sunset() - Time of sunset for a given day
    and location
  • date_sunrise() - Time of sunrise for a given day
    and location
  • time_nanosleep() - Delay for a number of seconds
    and nano seconds
  • Strings
  • str_split() - Convert a string to an array
  • strpbrk() - Search a string for any of a set of
    characters
  • substr_compare() - Binary safe optionally case
    insensitive comparison of two strings from an
    offset, up to length characters
  • Other
  • php_check_syntax() - Check the syntax of the
    specified file
  • php_strip_whitespace() - Return source with
    stripped comments and whitespace

73
Additional Resources
  • PHP Manual http//docs.php.net/
  • PHP Tutorial http//academ.hvcc.edu/kantopet/php/
    index.php
  • PHP Coder http//www.phpide.de/
  • JEdit http//www.jedit.org/
  • PHP's creator offers his thoughts on the PHP
    phenomenon, what has shaped and motivated the
    language, and where the PHP movement is heading
    http//www.oracle.com/technology/pub/articles/php_
    experts/rasmus_php.html
  • Hotscripts A large number of PHP scripts can be
    found at http//hotscripts.com/PHP/Scripts_and_Pr
    ograms/index.html

74
Resources
  • PHP Downloads and Online Documentation
  • www.php.net
  • Community
  • www.phpbuilder.com articles on PHP, discussion
    forums
  • www.phpresourceindex.com over 1,000 PHP scripts
  • www.phpvolcano.com PHP 5 information
  • Newsgroups
  • comp.lang.php

75
Questions?
  • Any Questions
  • www.php.net
  • Community
  • www.phpbuilder.com articles on PHP, discussion
    forums
  • Newsgroups
  • comp.lang.php

76
Exercise
77
STEP1 Install PHP
78
STEP2 Check the Installation
  • Create a test PHP page.
  • test.php

lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML
4.01//EN" "http//www.w3.org/TR/html4/st
rict.dtd"gt lthtmlgt ltheadgt lttitlegtPHP
Pagelt/titlegt lt/headgt ltbodygt lt? echo "lth1gtThe
First PHP Pagelt/h1gt" echo "ltpgtHello
World" ?gt lt/bodygt lt/htmlgt
79
STEP3 Check Options
  • Create a page which shows PHP options.

.... lt? phpinfo() ?gt ....
80
STEP4 Test FORM
  • Create an HTML page with FORM
  • input name, age
  • create submit button
  • Create a PHP page
  • show name and age

HTML
PHP
FORM
name XXXX age XX
name
age
submit
81
STEP5 Test Session
.... lt? if (!isset(_SESSION'count'))
_SESSION'count' 0 else
_SESSION'count' ?gt ltpgtcount
lt?_SESSION'count'?gtlt/pgt ltpgtlta
href"count.php"gtagainlt/agtlt/pgt ....
Write a Comment
User Comments (0)
About PowerShow.com