Web Programming in PHP - PowerPoint PPT Presentation

1 / 122
About This Presentation
Title:

Web Programming in PHP

Description:

... label must be put in the first position without any space or other characters. Example ... Set locale information. similar_text. Calculate the similarity ... – PowerPoint PPT presentation

Number of Views:107
Avg rating:3.0/5.0
Slides: 123
Provided by: hsian
Category:
Tags: php | keys | programming | web

less

Transcript and Presenter's Notes

Title: Web Programming in PHP


1
Web Programming in PHP
  • Dr. Hsiang-Fu Yu
  • National Taipei University of Education
  • Original by James Bowen

2
Reference Sites
  • http//www.php.net
  • http//www.php.net/manual
  • http//www.zend.com
  • http//www.zend.com/manual

3
PHP History
  • PHP originally stood for Personal Home Page
  • It started out, in 1994, as a simple preprocessor
    of HTML files
  • built by Rasmus Lerdorf (born in Greenland, grew
    up in Denmark and Canada, graduated from
    University of Waterloo in 1993, now prominent
    member of Open Source movement)
  • original purpose was to log people who viewed his
    on-line resume
  • Name now supposed to stand for Hypertext
    Pre-Processor

4
PHP History (cont.)
  • Initially, PHP comprised a simple parser plus a
    library of C functions
  • Scan a HTML file looking for instances of a new
    non-standard tag
  • Then replace the contents of these tag instances
    with the result of executing some functions in
    the C library
  • Thus, much PHP syntax looks like C
  • Other parts of it, however, have a Perl flavour

5
Enable PHP in HTTP (Web) Servers
  • PHP is available in Windows and all types of Unix
    environments
  • It is supported by Apache, AOLServer, Roxen and
    IIS
  • Here, we assume that the httpd recognizes a file
    who name has the suffix .php as a PHP file

6
A first PHP file
  • lthtmlgt
  • ltheadgt
  • lttitlegtPHP Testlt/titlegt
  • lt/headgt
  • ltbodygt
  • lt?php echo ltpgtHello Worldlt/pgt" ?gt
  • lt/bodygt
  • lt/htmlgt

7
How PHP files Are Processed
  • The httpd demon simply copies regular HTML
    content in the .php file to the message body that
    will be sent to a client which requests the .php
    file
  • The new non-standard tag is of the form
  • lt?php ?gt
  • The text inside the tag is PHP code
  • lt?php echo ltpgtHello Worldlt/pgt" ?gt
  • The httpd demon executes this PHP code and copies
    the output text, generated by this PHP code, to
    the message body that will be sent to the client
  • Thus, the client would see only
  • ltpgtHello Worldlt/pgt

8
Suppose That We Request This File
  • C\gt telnet 140.115.52.150 80
  • Trying 140.115.52.150...
  • Connected to dslab.csie.ncu.edu.tw.
  • Escape character is ''.
  • GET /index.php
  • lthtmlgt
  • ltheadgt
  • ltmeta http-equiv"refresh" content"0
    url94html/index.html"gt
  • lt/headgt
  • ltbodygt
  • lt/bodygt
  • lt/htmlgt
  • Connection closed by foreign host.

9
PHP Files Are Not Special
  • PHP files do not have to be executable
  • They can be regarded as simply HTML files with
    some new tags

10
PHP Tags
  • In the example just seen, the PHP tag was
  • lt?php ?gt
  • This is the best PHP tag to use it is the one
    which works best if we are also using XML,
    because it avoids conflicts with XML Processing
    Instructions
  • The following tags are also used
  • lt? ?gt
  • lt gt
  • ltscript languagephpgt lt/scriptgt

11
Variables in PHP
  • Variables in PHP are denoted by a dollar sign
    followed by the name of the variable
  • a, b
  • A variable name is case-sensitive, like C
  • A valid variable name starts with a letter or
    underscore, followed by any number of letters,
    numbers, or underscores, like C again

12
Example of Variables
  • lthtmlgt
  • ltheadgt
  • lttitlegtGreetingslt/titlegt
  • lt/headgt
  • ltbodygt
  • lth1gtGreetingslt/h1gt
  • ltpgt
  • lt?php person "Tom"
  • Person "Dick"
  • echo "Hello person and Person"
  • ?gt
  • lt/pgt
  • lt/bodygt
  • lt/htmlgt

13
Example of Variables (cont.)
14
Automatic Variables in PHP
  • One of the main benefits of PHP is that it
    provides lots of variables automatically
  • Consider, for example, the .php file on the next
    slide, _SERVERHTTP_USER_AGENT
  • It produces the output on the following two
    slides when viewed by MSIE 6.0 and Netscape 2.0

15
Example of Automatic PHP Variable
  • lthtmlgt
  • ltheadgt
  • lttitlegtYour browserlt/titlegt
  • lt/headgt
  • ltbodygt
  • lth1gtYour Browserlt/h1gt
  • ltpgt
  • You are using
  • lt?php echo _SERVERHTTP_USER_AGENT ?gt
  • to view this page.
  • lt/pgt
  • lt/bodygt
  • lt/htmlgt

16
Example of Automatic PHP Variable (cont.)
17
Example of Automatic PHP Variable (cont.)
18
Data Types in PHP
  • PHP supports eight primitive data types
  • There are four scalar types
  • boolean
  • integer
  • floating-point number
  • string
  • There are two structured types
  • array
  • object
  • There are two special data types
  • resource
  • NULL

19
Data Types in PHP (cont.)
  • The programmer does not need to specify the type
    of a variable
  • a variables type is determined from the context
    of its usage

20
Booleans
  • The boolean data type admits two values
  • true (case-insensitive)
  • false (case-insensitive)
  • Example
  • itIsRainingToday true
  • thePrinterIsBusy True
  • theQueueIsEmpty FALSE

21
Integers
  • Integers can be specified in decimal, hexadecimal
    or octal notation, optionally preceded by a sign
  • In octal notation, the number must have a leading
    0
  • In hexadecimal notation, the number must have a
    leading 0x.
  • Examples
  • a 1234 decimal number
  • a 0123 octal number (i.e., 83 decimal)
  • a -123 a negative number
  • a 0x1B hexadecimal number (i.e., 27 decimal)

22
Integers (cont.)
  • The maximum size of an integer is
    platform-dependent, but usually its 32 bits
    signed about 2,000,000,000
  • PHP does not support unsigned integers.

23
Floating Point Numbers
  • Specified using any of these forms
  • a 1.234
  • a 1.2e3
  • a 7E-10
  • The maximum size of a float is platform-dependent,
    although most support a maximum of about 1.8e308
    with a precision of roughly 14 decimal digits

24
Strings
  • Specified in three different ways
  • single quoted
  • double quoted
  • heredoc syntax

25
Single-quoted Strings
  • In single-quoted strings, single-quotes and
    backslashes must be escaped with a preceding
    backslash
  • echo 'this is a simple string'
  • echo 'You can embed newlines in strings,
  • just like this.'
  • echo Douglas MacArthur said "I\'ll be back when
    leaving the Phillipines'
  • echo 'Are you sure you want to delete C\\.?'

26
Double-quoted Strings
  • In double-quoted strings,
  • variables are interpreted to their values, and
  • various characters can be escaped
  • \n linefeed
  • \r carriage return
  • \t horizontal tab
  • \\ backslash
  • \ dollar sign
  • \ double quote
  • \0-71,3 a character in octal notation
  • \x0-9A-Fa-f1,2 a character in hexadecimal
    notation

27
Heredoc Strings
  • Heredoc strings are like double-quoted strings
    without the double quotes
  • A heredoc string is delimited as follows
  • The string is preceded by ltltlt followed by a label
  • The string followed by a 2nd occurrence of the
    same label
  • Note the second label must be put in the first
    position without any space or other characters
  • Example
  • str ltltltEOD
  • Example of string
  • spanning multiple lines using heredoc syntax.
  • EOD

28
Functions for Strings
  • addcslashes
  • Quote string with slashes in a C style
  • addslashes
  • Quote string with slashes
  • bin2hex
  • Convert binary data into hexadecimal
    representation
  • chop
  • Alias of rtrim()
  • chr
  • Return a specific character

29
Functions for Strings (cont.)
  • chunk_split
  • Split a string into smaller chunks
  • convert_cyr_string
  • Convert from one Cyrillic character set to
    another
  • count_chars
  • Return information about characters used in a
    string
  • crc32
  • Calculates the crc32 polynomial of a string
  • crypt
  • One-way string encryption (hashing)

30
Functions for Strings (cont.)
  • echo
  • Output one or more strings
  • explode
  • Split a string by string
  • get_html_translation_table
  • Returns the translation table used by
    htmlspecialchars() and htmlentities()
  • get_meta_tags
  • Extracts all meta tag content attributes from a
    file and returns an array

31
Functions for Strings (cont.)
  • hebrev
  • Convert logical Hebrew text to visual text
  • hebrevc
  • Convert logical Hebrew text to visual text with
    newline conversion
  • htmlentities
  • Convert all applicable characters to HTML
    entities
  • htmlspecialchars
  • Convert special characters to HTML entities
  • implode
  • Join array elements with a string

32
Functions for Strings (cont.)
  • join
  • Join array elements with a string
  • levenshtein
  • Calculate Levenshtein distance between two
    strings
  • localeconv
  • Get numeric formatting information
  • ltrim
  • Strip whitespace from the beginning of a string

33
Functions for Strings (cont.)
  • md5
  • Calculate the md5 hash of a string
  • md5_file
  • Calculates the md5 hash of a given filename
  • metaphone
  • Calculate the metaphone key of a string
  • nl2br
  • Inserts HTML line breaks before all newlines in a
    string
  • ord
  • Return ASCII value of character

34
Functions for Strings (cont.)
  • parse_str
  • Parses the string into variables
  • print
  • Output a string
  • printf
  • Output a formatted string
  • quoted_printable_decode
  • Convert a quoted-printable string to an 8 bit
    string
  • quotemeta
  • Quote meta characters

35
Functions for Strings (cont.)
  • str_rot13
  • Perform the rot13 transform on a string
  • rtrim
  • Strip whitespace from the end of a string
  • sscanf
  • Parses input from a string according to a format
  • setlocale
  • Set locale information
  • similar_text
  • Calculate the similarity between two strings

36
Functions for Strings (cont.)
  • soundex
  • Calculate the soundex key of a string
  • sprintf
  • Return a formatted string
  • strncasecmp
  • Binary safe case-insensitive string comparison of
    the first n characters
  • strcasecmp
  • Binary safe case-insensitive string comparison
  • strchr
  • Find the first occurrence of a character

37
Functions for Strings (cont.)
  • strcmp
  • Binary safe string comparison
  • strcoll
  • Locale based string comparison
  • strcspn
  • Find length of initial segment not matching mask
  • strip_tags
  • Strip HTML and PHP tags from a string
  • stripcslashes
  • Un-quote string quoted with addcslashes()

38
Functions for Strings (cont.)
  • stripslashes
  • Un-quote string quoted with addslashes()
  • stristr
  • Case-insensitive strstr()
  • strlen
  • Get string length
  • strnatcmp
  • String comparisons using a "natural order"
    algorithm

39
Functions for Strings (cont.)
  • strnatcasecmp
  • Case insensitive string comparisons using a
    "natural order" algorithm
  • strncmp
  • Binary safe string comparison of the first n
    characters
  • str_pad
  • Pad a string to a certain length with another
    string
  • strpos
  • Find position of first occurrence of a string

40
Functions for Strings (cont.)
  • strrchr
  • Find the last occurrence of a character in a
    string
  • str_repeat
  • Repeat a string
  • strrev
  • Reverse a string
  • strrpos
  • Find position of last occurrence of a char in a
    string
  • strspn
  • Find length of initial segment matching mask

41
Functions for Strings (cont.)
  • strstr
  • Find first occurrence of a string
  • strtok
  • Tokenize string
  • strtolower
  • Make a string lowercase
  • strtoupper
  • Make a string uppercase
  • str_replace
  • Replace all occurrences of the search string with
    the replacement string

42
Functions for Strings (cont.)
  • strtr
  • Translate certain characters
  • substr
  • Return part of a string
  • substr_count
  • Count the number of substring occurrences
  • substr_replace
  • Replace text within a portion of a string
  • trim
  • Strip whitespace from the beginning and end of a
    string

43
Functions for Strings (cont.)
  • ucfirst
  • Make a string's first character uppercase
  • ucwords
  • Uppercase the first character of each word in a
    string
  • vprintf
  • Output a formatted string
  • vsprintf
  • Return a formatted string

44
Functions for Strings (cont.)
  • wordwrap
  • Wraps a string to a given number of characters
    using a string break character.
  • nl_langinfo
  • Query language and locale information

45
Arrays
  • An array in PHP is a structure which maps keys to
    values
  • The keys can specified explicitly or they can be
    omitted
  • If keys are omited, integers starting with 0 are
    keys
  • The value mapped to a key can, itself, be an
    array, so we can have nested arrays

46
Create An Array
  • A special function is used to specify arrays
  • array()
  • Format of Usage
  • array(key gt value, )
  • A key is either a string or a non-negative
    integer
  • A value can be anything

47
Create An Array (cont.)
  • Format of array creation
  • array( key gt value, ... )
  • A hash array
  • mothers array (tom"gtmary", mick"gtann",
    bill"gtorla")
  • Implicit indices are integers, starting at 0
  • places array (Cork, Dublin, Galway)

48
Create An Array (cont.)
  • If an explicit integer index is followed by
    implicit indices, they follow on from the highest
    previous index
  • Here is an array indexed by integers 1, 2, 3
  • places array (1 gt Cork, Dublin,
    Galway)
  • Here is an array indexed by integers 1, 5, 6
  • places array (5gt Cork, 1 gt Dublin,
    Galway)

49
Create An Array (cont.)
  • A two-dimensional hash array
  • parents
  • array ( tom gt array (father gt bill,
    mothergt mary),
  • dave gt array(father gt
    tom, mother gt orla))
  • A two-dimensional ordinary array
  • heights
  • array (array (10,20),
  • array(100,200))

50
Array Example 1
  • lthtmlgt
  • ltheadgtlttitlegtArray Demolt/titlegtlt/headgt
  • ltbodygt
  • lth1gtArray Demolt/h1gt
  • ltpgt
  • lt?php
  • capital array ('France'gt'Paris','Irelan
    d'gt'Dublin')
  • echo 'The capital of Ireland is '
  • echo capital'Ireland'
  • ?gt
  • lt/pgt
  • lt/bodygt
  • lt/htmlgt

51
Array Example 1 (cont.)
52
Array Example 2
  • lthtmlgt
  • ltheadgtlttitlegtArray Demolt/titlegtlt/headgt
  • ltbodygt
  • lth1gtArray Demolt/h1gt
  • ltpgt
  • lt?php
  • capital array ('France'gt'Paris',
    Ireland'gt'Dublin')
  • echo "The various capitals are\nltulgt"
  • foreach (capital as city) echo
    "ltligtcitylt/ligt"
  • echo "lt/ulgt"
  • ?gt
  • lt/pgt
  • lt/bodygt
  • lt/htmlgt

53
Array Example 2
54
Array Example 3
  • lthtmlgt
  • ltheadgtlttitlegtArray Demolt/titlegtlt/headgt
  • ltbodygt
  • lth1gtArray Demolt/h1gt
  • ltpgt
  • lt?php
  • capital array ('France'gt'Paris',
    'Ireland'gt'Dublin')
  • echo "The various capitals are\nltulgt"
  • foreach (capital as country gt city)
  • echo "ltligtThe capital of country
    is citylt/ligt"
  • echo "lt/ulgt"
  • ?gt
  • lt/pgt
  • lt/bodygt
  • lt/htmlgt

55
Array Example 3
56
Array Example 4
  • lthtmlgt
  • ltheadgt
  • lttitlegtDetails about Fredlt/titlegt
  • lt/headgt
  • ltbodygt
  • lth1gtDetails about Fredlt/h1gt
  • lt?php
  • ages array ("Fred" gt 2, "Tom"gt 45)
  • parents array ("Fred" gt array("father" gt
    "Tom", "mother"gt"Mary"))
  • print "ltpgt Fred's age is "
  • print ages"Fred"
  • print ".lt/pgt"
  • print "ltpgtHis father is "
  • print parents"Fred""father"
  • print ".lt/pgt"
  • ?gt
  • lt/bodygt
  • lt/htmlgt

57
Array Example 4
58
Functions for Array
  • array
  • Create an array
  • array_change_key_case
  • Returns an array with all string keys lowercased
    or uppercased
  • array_chunk
  • Split an array into chunks
  • array_count_values
  • Counts all the values of an array
  • array_diff
  • Computes the difference of arrays

59
Functions for Array (cont.)
  • array_filter
  • Filters elements of an array using a callback
    function
  • array_flip
  • Flip all the values of an array
  • array_fill
  • Fill an array with values
  • array_intersect
  • Computes the intersection of arrays
  • array_key_exists
  • Checks if the given key or index exists in the
    array

60
Functions for Array (cont.)
  • array_keys
  • Return all the keys of an array
  • array_map
  • Applies the callback to the elements of the given
    arrays
  • array_merge
  • Merge two or more arrays
  • array_merge_recursive
  • Merge two or more arrays recursively
  • array_multisort
  • Sort multiple or multi-dimensional arrays

61
Functions for Array (cont.)
  • array_pad
  • Pad array to the specified length with a value
  • array_pop
  • Pop the element off the end of array
  • array_push
  • Push one or more elements onto the end of array
  • array_rand
  • Pick one or more random entries out of an array
  • array_reverse
  • Return an array with elements in reverse order

62
Functions for Array (cont.)
  • array_reduce
  • Iteratively reduce the array to a single value
    using a callback function
  • array_shift
  • Shift an element off the beginning of array
  • array_slice
  • Extract a slice of the array
  • array_splice
  • Remove a portion of the array and replace it with
    something else

63
Functions for Array (cont.)
  • array_sum
  • Calculate the sum of values in an array.
  • array_unique
  • Removes duplicate values from an array
  • array_unshift
  • Prepend one or more elements to the beginning of
    array
  • array_values
  • Return all the values of an array
  • array_walk
  • Apply a user function to every member of an array

64
Functions for Array (cont.)
  • arsort
  • Sort an array in reverse order and maintain index
    association
  • asort
  • Sort an array and maintain index association
  • compact
  • Create array containing variables and their
    values
  • count
  • Count elements in a variable
  • current
  • Return the current element in an array

65
Functions for Array (cont.)
  • each
  • Return the current key and value pair from an
    array and advance the array cursor
  • end
  • Set the internal pointer of an array to its last
    element
  • extract
  • Import variables into the current symbol table
    from an array
  • in_array
  • Return TRUE if a value exists in an array

66
Functions for Array (cont.)
  • array_search
  • Searches the array for a given value and returns
    the corresponding key if successful
  • key
  • Fetch a key from an associative array
  • krsort
  • Sort an array by key in reverse order
  • ksort
  • Sort an array by key
  • list
  • Assign variables as if they were an array

67
Functions for Array (cont.)
  • natsort
  • Sort an array using a "natural order" algorithm
  • natcasesort
  • Sort an array using a case insensitive "natural
    order" algorithm
  • next
  • Advance the internal array pointer of an array
  • pos
  • Get the current element from an array
  • prev
  • Rewind the internal array pointer

68
Functions for Array (cont.)
  • range
  • Create an array containing a range of elements
  • reset
  • Set the internal pointer of an array to its first
    element
  • rsort
  • Sort an array in reverse order
  • shuffle
  • Shuffle an array
  • sizeof
  • Get the number of elements in variable

69
Functions for Array (cont.)
  • sort
  • Sort an array
  • uasort
  • Sort an array with a user-defined comparison
    function and maintain index association
  • uksort
  • Sort an array by keys using a user-defined
    comparison function
  • usort
  • Sort an array by values using a user-defined
    comparison function

70
Objects
  • PHP supports object-oriented programming
  • The subject is too big to cover here
  • But heres an example
  • lt?php
  • class thingAMeBob
  • function say_hello()
  • echo Hello, World!"
  • thing1 new thingAMeBob
  • thing1-gtsay_hello()
  • ?gt

71
Resources
  • This data type is used for maintaining links to
    external resources, such as data bases etc.
  • A full treatment is beyond our scope here

72
The NULL data type
  • This data type contains only one value
  • NULL
  • It is case-insensitive
  • This is a value which is returned when some
    expression has no value
  • Example
  • capital array ('France'gt'Paris',
    'Ireland'gt'Dublin')
  • capitalOfEngland capitalEngland
  • In this case, capitalOfEngland would get the
    value NULL

73
Changing Data Type
  • PHP will, in some circumstances, change the type
    of a datum
  • For example, it will treat a string of digits as
    a number if it finds in an arithmetic expression
  • PHP also supports type casting
  • lt?php myInteger 12
  • myFloat 1.3
  • result myFloat (float)
    myInteger
  • echo result ?gt

74
Automatic Variables (again)
  • PHPs automatic variables come from the following
    sources
  • the Environment
  • query expressions in GET requests
  • message bodies in POST requests
  • cookies
  • the Server

75
CGI Environment Variables
  • CGI environment variables are automatically
    available
  • Example
  • lthtmlgt
  • ltheadgtlttitlegtWhat I know about yoult/titlegtlt/headgt
  • ltbodygt
  • lth1gtI know some things about yoult/h1gt
  • lt?php
  • echo "ltpgtYou are using ._SERVERHTTP_USER_AGENT
    . to view this page.lt/pgt"
  • echo "ltpgtYou used the ._SERVERREQUEST_METHOD
    . request method.lt/pgt"
  • echo "ltpgtYou used this request URI
    ._SERVERREQUEST_URI..lt/pgt"
  • echo "ltpgtYou accessed this host URI
    ._SERVERHTTP_HOST..lt/pgt"
  • echo "ltpgtYou used this protocol
    ._SERVERSERVER_PROTOCOL..lt/pgt"
  • ?gt
  • lt/bodygt
  • lt/htmlgt

76
Example (cont.)
77
Form Variables (via either GET or POST)
  • These are automatically available
  • Example Form
  • lthtmlgtltheadgtlttitlegtApplication Formlt/titlegtlt/headgt
  • ltbodygt
  • ltform method"POST" action"file9.php"gt
  • ltpgtYour surname ltinput type"text"
    name"surnamegtlt/pgt
  • ltpgtYour address ltinput type"text"
    name"addressgtlt/pgt
  • ltbutton type"submit"gtPlease send me the
    brochure.lt/buttongt
  • lt/formgt
  • lt/bodygtlt/htmlgt
  • Example Response Generator, file9.php
  • lthtmlgtltheadgtlttitlegtThank yoult/titlegtlt/headgt
  • ltbodygt
  • lth1gtThank yoult/h1gt
  • ltpgtThank you,lt?php echo _POSTsurname ?gt.
  • We will send our brochure to lt?php echo
    _POSTaddress ?gt.lt/pgt
  • lt/bodygt
  • lt/htmlgt

78
Example (cont.)
79
Example (cont.)
80
Example (cont.)
81
Control Structures if Statements
  • if (a gt b)
  • echo "a is bigger than b"
  • if (a gt b)
  • print "a is bigger than b"
  • b a
  • if (a gt b)
  • print "a is bigger than b"
  • else print "a is NOT bigger than b"
  • if (a gt b)
  • print "a is bigger than b"
  • elseif (a b)
  • print "a is equal to b"
  • else print "a is smaller than b

82
Control Structures if Statements (cont.)
  • Example
  • lthtmlgt
  • ltheadgtlttitlegtYour browserlt/titlegtlt/headgt
  • ltbodygt
  • lth1gtYour Browserlt/h1gt
  • ltpgt
  • lt?php
  • if( strstr(_SERVERHTTP_USER_AGENT,
    "MSIE") )
  • echo "You are using Internet
    Explorer"
  • ?gt
  • to view this page.
  • lt/pgt
  • lt/bodygt
  • lt/htmlgt
  • strstr is a boolean function which checks if its
    2nd argument is a substring of its 1st

83
Control Constructs -- while
  • These are just like their counterparts in C
  • i 1
  • while ( i lt 10 )
  • echo i
  • i 0
  • do print i while (igt0)

84
Control Constructs -- for
  • These are just like their counterparts in C
  • for (i 1 i lt 10 i)
  • print i

85
Control Constructs -- foreach
  • These are similar their counterparts in Perl
  • foreach(array_expression as value)
  • statement
  • foreach(array_expression as key gt value)
  • statement

86
Jumping In and Out of PHP Mode
  • We can can jump in and out of PHP mode even in
    the middle of a PHP block
  • lt?php
  • if(strstr(_SERVERHTTP_USER_AGENT, "MSIE"))
  • ?gt ltpgtYou are using Internet
    Explorerlt/pgt lt?php
  • else ?gt ltpgtYou are not using Internet
    Explorerlt/pgt lt?php
  • ?gt
  • Instead of using an echo statement to print
    something, we jumped out of PHP mode
  • Note that the logical flow of the PHP remains
    intact
  • Only one of the HTML blocks will be sent to the
    user

87
A Form Example file10.php
  • lthtmlgt
  • ltheadgtlttitlegtApplication Handlerlt/titlegtlt/headgt
  • ltbodygt
  • lt?php
  • if (! _GETsurname)
  • ?gt ltform methodGET" action"file10.php"gt
  • ltpgtYour surname ltinput type"text"
    name"surname"gtlt/pgt
  • ltpgtYour address ltinput type"text"
    name"address"gtlt/pgt
  • ltbutton type"submit"gtPlease send me the
    brochure.lt/buttongt
  • lt/formgt
  • lt?php
  • else echo "ltpgtThank you, ._GETsurname..lt/
    pgt"
  • echo "ltpgtWe will write to you at
    ._GETaddress..lt/pgt" ?gt
  • lt/bodygt
  • lt/htmlgt

88
A Form Example (cont.)
89
A Form Example (cont.)
90
A Form Example (cont.)
91
A Request for This Resource No Query or Message
Body
  • gt telnet 210.240.185.203 80
  • Trying 210.240.185.203...
  • Connected to netprg.ntue.edu.tw.
  • Escape character is ''.
  • GET http//210.240.185.203/yu/file10.php

92
Response to Request with No Query or Message Body
  • HTTP/1.1 200 OK
  • Date Fri, 08 Feb 2002 112140 GMT
  • Server Apache/1.3.20 (Unix) PHP/4.0.6
  • X-Powered-By PHP/4.0.6
  • Transfer-Encoding chunked
  • Content-Type text/html
  • 160
  • lthtmlgt
  • ltheadgtlttitlegtApplication Handlerlt/titlegtlt/headgt
  • ltbodygt
  • ltform methodGET"
  • action"file10.php"gt
  • ltpgtYour surname ltinput type"text"
    name"surname"gtlt/pgt
  • ltpgtYour address ltinput type"text"
    name"address"gtlt/pgt
  • ltbutton type"submit"gtPlease send me the
    brochure.lt/buttongt
  • lt/formgt
  • lt/bodygt
  • lt/htmlgt

93
Another Request Containing a Query
  • gt telnet 210.240.185.203 80
  • Trying 210.240.185.203...
  • Connected to netprg.ntue.edu.tw.
  • Escape character is ''.
  • GET http//210.240.185.203/yu/file10.php?surname
    doyle

94
Response to Request Containing a Query
  • HTTP/1.1 200 OK
  • Date Fri, 08 Feb 2002 113101 GMT
  • Server Apache/1.3.20 (Unix) PHP/4.0.6
  • X-Powered-By PHP/4.0.6
  • Transfer-Encoding chunked
  • Content-Type text/html
  • 88
  • lthtmlgt
  • ltheadgtlttitlegtApplication Handlerlt/titlegtlt/headgt
  • ltbodygt
  • ltpgtThank you, doyle.lt/pgtltpgt We will write to you
    at .lt/pgtlt/bodygt
  • lt/htmlgt
  • 0
  • Connection closed by foreign host.
  • gt

95
Finding Out about Your PHP Environment
  • One of the pre-defined PHP functions is phpinfo()
  • lthtmlgt
  • ltbodygt
  • lth1gtYour PHP Environmentlt/h1gt
  • lt?php phpinfo() ?gt
  • lt/bodygt
  • lt/htmlgt
  • In what follows, notice that MySQL support is
    enabled

96
Finding Out about Your PHP Environment (cont.)
97
Finding Out about Your PHP Environment (cont.)
98
Finding Out about Your PHP Environment (cont.)
99
Finding Out about Your PHP Environment (cont.)
100
Finding Out about Your PHP Environment (cont.)
101
Finding Out about Your PHP Environment (cont.)
102
Finding Out about Your PHP Environment (cont.)
103
Finding Out about Your PHP Environment (cont.)
104
Finding Out about Your PHP Environment (cont.)
105
Finding Out about Your PHP Environment (cont.)
106
A MySQL Database
  • mysqlgt
  • mysqlgt use cs4400db
  • mysqlgt select from student
  • ------------------------------
  • name sex birth
  • ------------------------------
  • john brown m 1980-01-05
  • bill brown m 1980-11-23
  • ------------------------------
  • mysqlgt

107
A PHP Program Displaying The Database
  • lthtmlgt
  • ltheadgtlttitlegtThe Student Databaselt/titlegtlt/headgt
  • ltbodygt
  • lth1gtThe Student Databaselt/h1gt
  • lt?php
  • db mysql_connect("localhost", "root",
    myRealPassword")
  • mysql_select_db("cs4400db",db)
  • result mysql_query("SELECT FROM
    student",db) ?gt
  • lttable rulesallgt
  • lttheadgtlttrgtltthgtNamelt/thgtltthgtSexlt/thgtltthgtPositionlt/
    thgtlt/trgtlt/theadgt
  • lttbodygt
  • lt?php
  • while (myrow mysql_fetch_array(result))
  • printf("lttrgtlttdgtslt/tdgtlttdgtslt/tdgtlttdgtslt/tdgt
    lt/trgt\n",
  • myrowname, myrowsex,
    myrowbirth) ?gt
  • lt/tbodygt
  • lt/tablegt
  • lt/bodygt
  • lt/htmlgt

108
A PHP Program Displaying The Database (cont.)
109
File Upload Form
  • lthtmlgt
  • ltheadgt
  • lttitlegtUpload a Filelt/titlegt
  • lt/headgt
  • ltbodygt
  • lth1gtUpload a Filelt/h1gt
  • ltform enctype"multipart/form-data" method"post"
    action"uploadFile.php"gt
  • ltpgtFile to Upload
  • ltinput type"file" nameuserfile" size"30"gtlt/pgt
  • ltpgtltbutton type"submitgtUpload Filelt/buttongtlt/pgt
  • lt/formgt
  • lt/bodygt
  • lt/htmlgt

110
File Upload Script uploadFile.php
  • lt?php
  • if ( _FILES'userfile''name' ! "" )
  • copy(_FILES'userfile''tmp_name',
  • "/tmp/"._FILES'userfile''name'
    )
  • or die("Could not copy the file! Are directory
    permissions correct?")
  • else
  • die("You did not specify an input file")
  • ?gt
  • lthtmlgtltheadgtlttitlegtFile Receivedlt/titlegt
  • ltbodygtlth1gtFile Receivedlt/h1gt
  • ltpgtThe following file has been received
  • lt?php
  • echo _FILES'userfile''name' ?gt,
  • containing lt?php echo _FILES'userfile''size'
    ?gt bytes
  • and of MIME type lt?php echo _FILES'userfile'
    'type' ?gt
  • .lt/pgtlt/bodygtlt/htmlgt

111
File Upload
112
File Upload (cont.)
113
File Upload (cont.)
114
Controlling Headers/Status Lines with PHP
115
Sending Headers in PHP
  • PHP enables you to have some control over status
    lines and response headers
  • PHP provides a built-in function, header(), which
    can be used to set HTTP header lines in a
    response message
  • The function name is mis-leading it can also,
    within limits, be used to control the HTTP status
    line
  • Format
  • header ( some-string , some-boolean)

116
Sending Headers in PHP (cont.)
  • Example calls
  • header('WWW-Authenticate Negotiate')
  • header('WWW-Authenticate NTLM, false)
  • By default, a second header of the same type will
    replace an earlier one of the same type
  • If false is sent as the optional boolean
    parameter, the header will not replace an earlier
    one of the same type

117
Sending Headers in PHP (cont.)
  • PHP treats two type of call to header() in a
    special way
  • If you use header() to send a Location header,
    PHP will auatomatgically change the code in the
    status line of the response to be 302 (REDIRECT)
  • header("Location https//"._SERVER'HTTP_HOST'.
    "/index.php")
  • The second special case is any header that starts
    with the string, "HTTP/" (case is not
    significant)
  • this will be used, within the limits of
    predefined standard values, to control the status
    line
  • header("HTTP/1.0 404 Not Found")

118
User-authentication in PHP
  • The header() function can be used to send headers
    requiring authentication
  • This will cause a browser to pop up a
    username/password/realm dialog window and
  • When the values have been provided, send a new
    request back to the same page containing the
    appropriate information
  • This time, some special PHP variables will be
    set
  • _SERVERPHP_AUTH_USER
  • _SERVERPHP_AUTH_PW
  • _SERVERPHP_AUTH_TYPE

119
User-authentication in PHP (contd.)
  • The code below captures the users name and
    password
  • lt?php
  • if (! isset( _SERVERPHP_AUTH_USER ))
  • header("HTTP/1.0 401 Unauthorized")
  • header("WWW-Authenticate Basic
    realm\BankAccounts\"")
  • echo You must identify yourself."
  • else echo "ltpgtHello ._SERVERPHP_AUTH_USER.
    .lt/pgt"
  • echo "ltpgtYour password is
    ._SERVERPHP_AUTH_PW. lt/pgt"
  • ?gt

120
User-authentication in PHP (cont.)
  • The PHP_AUTH variables will not be set if
    external authentication is enabled for that
    particular page.
  • This is to prevent a script which reveals the
    password for a page that was protected through a
    traditional external mechanism, such as the
    .htpasswd mechanism
  • In this case, the _SERVERREMOTE_USER
    variable can be used to identify the
    externally-authenticated user.

121
Handling Cookies in PHP
  • PHP provides a function called setcookie() which
    can be used to send cookies to a browser
  • Since cookies are sent in HTTP headers, this
    function must be called before any ordinary
    content (such as HTML) is sent
  • Cookies sent from a broswer to a client will be
    converted into automatically created variables
  • Like those that are created to present data which
    come in GET and POST requests

122
Image Handling
  • As well as generating dynamic HTML, PHP can
    generate and manipulate images
  • lt?php
  • header("Content-type image/png")
  • stringimplode(argv," ")
  • im imageCreateFromPng("images/button1.png")
  • orange ImageColorAllocate(im, 220, 210, 60)
  • px (imagesx(im)-7.5strlen(string))/2
  • imageString(im,3,px,9,string,orange)
  • imagePng(im)
  • imageDestroy(im)
  • ?gt
Write a Comment
User Comments (0)
About PowerShow.com