Chapter%206%20 - PowerPoint PPT Presentation

About This Presentation
Title:

Chapter%206%20

Description:

suppose we want to test to see that a client inputs a valid area code. first -- what do we know about area codes -- 3 digits -- first digit can't be 0 -- can't be 911 ... – PowerPoint PPT presentation

Number of Views:856
Avg rating:3.0/5.0
Slides: 22
Provided by: jackd64
Category:
Tags: area | chapter | code

less

Transcript and Presenter's Notes

Title: Chapter%206%20


1
Chapter 6 Creating Web Forms and Validating
User Inputspring into PHP 5by Steven Holzner
  • Slides were developed by Jack DavisCollege of
    Information Scienceand TechnologyRadford
    University

2
Developing Web Applications
  • In developing web application, building the forms
    is just the first step in collecting data.
    Validating input data must be done to avoid
    wasted processing and to reduce effective
    response time.A typical code structure that
    validates data might bevalidate_data()if
    (count(errors) ! 0)
    display_errors() display_welcome()
    else process_data()

3
Displaying All Form Data
  • Here's a program that will display all the data
    being sent to the server program, a very useful
    debugging toollt?php foreach(_REQUEST as key
    gt val) if(is_array(val))
    foreach(val as item)
    echo key, " gt ", val,
    "ltbr /gt"
    else echo key, " gt ",
    val, "ltbr /gt" ?gt

4
Server Variables
  • There's a special superglobal array, _SERVER,
    that contains a great deal of information about
    what's going on with your web application. For
    example, _SERVER'REQUEST_METHOD' holds the
    request method that was used ("GET", "POST", and
    so on)'AUTH_TYPE' holds the
    authentication type'DOCUMENT_ROOT'
    root directory under which the script
    is executing, defined in server
    config'GATEWAY_INTERFACE' revision of
    the CGI spec. that the server is
    using, i.e., CGI/1.1'PHP_SELF'
    filename of the currently executing
    script'REMOTE_ADDR' ip address from
    which the user is viewing the current
    page

5
Server Variables (cont.)
  • 'REQUEST_METHOD' request method used to
    access the page -- GET, POST, HEAD,
    PUT'SERVER_NAME' name of the server host
    under which the script is
    executingthere are more see page 170 171 in
    your text

6
Useful HTTP Headers
  • A number of HTTP headers are built into the
    _SERVER array as well. For example,
    _SERVER'HTTP_USER_AGENT' holds the type of the
    user's browser.Some of the other entries
    --'HTTP_REFERER' the address of the
    page (if any) that referred the user
    agent to the current page.'HTTP_USER_AG
    ENT' text in the user_agent header from
    the current request, if there is one.
    Denotes the browser that is accessing
    the page.

7
Redirecting with HTTP Headers
  • You can read and create HTTP headers to send back
    to the browser. The header() function is used to
    create HTTP headers in the following
    scriptthe button value in the form has one of
    the following values (the names of php
    files)phpbuttonsphplistboxphptextareaTo
    redirect via a php scriptlt?php redirect
    "Location " .
    _REQUEST'Button' . ".html"echo
    header(redirect)?gtredirecting is often used
    with image maps

8
Custom Arrays for Form Data
  • You can use PHP to create a custom array for form
    data by giving each text field control a name
    with square bracketsSet the name attribute in
    the form field as in the followingltinput
    name"textdataname" type"text"
    size"20" maxlength"30" /gtin the receiving
    scriptlt?php text _REQUEST'textdata'
    echo text'name'?gt

9
Single PHP Page Application
  • Many web applications are written with a single
    PHP page. Say you wanted to get a single piece
    of data (like name) from a user and then you
    wanted to display that name with some other
    request for datalthtmlgtltheadgtlttitlegtSingle PHP
    Pagelt/titlegtlt/headgtltbodygt lth2gtUsing Text
    Fieldslt/h2gt lt?php if
    (isset(_REQUEST"Name")) ?gt
    lth2gt Using Text Fieldslt/h2gt ltpgtYour name
    islt?php echo _REQUEST"Name"
    else ?gtltform method"post" action"phptext.php"
    gtWhat's your name?ltinput name"name"
    type"text" /gtltbr /gtltbr/gt

10
Single Page App (Cont.)
  • ltinput type"submit" value"submit"
    /gtlt/formgtlt?php ?gtlt/bodygtlt/htmlgt

11
Validating Data
  • assume we're getting a name in a text fieldIf
    there's no entry in the text field we can check
    like in the followingfunction
    validate_data() global errors if
    (_REQUEST"Name" "") errors
    "ltspan style\"border-stylered
    colorblue\"gt .
    Please enter your name.
    lt/spangt" Note the structure for an
    php/html documentthat includes a validating
    function.((slide 2)) pp. 181-185 in your text

12
Regular Expressions
  • PHP can implement regular expressions for pattern
    matching. This is the way most validation of
    entered data is accomplished.Here are three
    functions used in pattern matching.ereg(),
    split(), ereg_replaceUse ereg(), to check if a
    string contains a match patternret
    ereg("search pattern", "target string")ret
    will be set to 1if the pattern is found 0
    otherwisesearch pattern is the regular
    expressiontarget string is the string to be
    searched

13
Pattern Matching Example
  • name 'Jake Jackson'pattern 'ke'if
    (ereg(pattern, name)) print
    ("Match") else print ("No
    match")outputs match since "ke" is
    foundregular expressions are defined by an
    industry standard IEEE POSIX 1003.2
    standardthere are several special characters
    that can be used to build patterns means the
    pattern must appear at the start of the
    target string means the pattern must appear
    at the end of the target string

14
Pattern Matching Characters
  • matches 1 or more occurrences
    matches 0 or more occurrences? matches 0 or
    1 occurrences. wildcard symbol matches any
    single character or symbol either
    pattern can be matched any of the included
    set can be matched at the beginning of
    the set means not these characters
    specify a number of repetitions of a
    character in the pattern-- note there are more,
    but these provide a good start

15
Pattern Matching Example
  • suppose we want to test to see that a client
    inputs a valid area codefirst -- what do we
    know about area codes -- 3 digits --
    first digit can't be 0 -- can't be 911
  • remember we can group characters using
    parentheses

16
Predefined Character Classes
  • there are several predefined character classes
    that are typically used in pattern matching
    regular expressionsspace matches a
    single spacealpha matches any word
    character (uppercase or
    lowercase letters)upper matches any
    single uppercase
    letterlower matches any single
    lowercase
    letterdigit matches any valid digit
    (0-9)punct matches an punctuation
    mark (? , . " ' !
    )

17
Using split()
  • use split() to break a string into different
    pieces based on the presence of a match
    patternoutput split(search_patt, target_st,
    max)output -- is an array variable that will
    contain the matchessearch_patt
    -- this is the pattern to be matchedtarget_st
    -- the string to be searchedmax -- maximum
    number of matches to make (this
    parameter is optional)line 'Baseball, hot
    dogs, apple pie'item split ( ','
    ,line)item0 will contain Baseballitem1
    will contain hot dogsitem2 will contain
    apple pie

18
eregreplace()
  • works like ereg, but a second string is specified
    to replace the part of the target string that
    matches the patternstart 'AC1001Hammer1515
    0'end eregreplace('Hammer', 'Drill',
    start)end will now contain
    'AC1001Drill15150'

19
Removing HTML Tags from Input
  • something you must watch out for --- html in a
    user's text box, especially if you're going to
    display that text. Malicious users can put some
    nasty HTML (including JavaScripts) into submitted
    text, which would be executed if you display that
    text in a browser. You can use the PHP
    strip_tags function to remove all HTML tags from
    text.function process_data() ok_text
    strip_tags(_REQUEST"name")
  • if you don't want to strip HTML tags, but you
    want to render them harmless, you can use the
    htmlentities function instead, which encodes HTML
    tags. For example, ltbgtCharleslt/bgt would be
    converted to ltbgtCharleslt/bgta
    browser will display this as ltbgtCharleslt/bgt

20
Validating with JavaScript
  • using JavaScript embedded in an input form
    provides for validation of data before it's sent
    to the server. ltform name"fm1"
    action"servpg.php" method"post"
    onsubmit"return checker()" gtonce the
    user clicks on the submit button the checker()
    javascript will be run. It can do pattern
    matching and other validation on the data in the
    form fields. If it returns false, the query
    string will not be sent to the server
    application. If it returns true, it will. If
    the javascript detects a problem with the data it
    can post a message to the user (typically using a
    dialog box) which will prompt them to correct the
    data. After the correction is made the user can
    submit the data again.

21
HTTP authentication
  • PHP allows you to determine whether the user has
    been authorized by checking the PHP_AUTH_USER key
    in _SERVER. If _SERVER'PHP_AUTH_USER' has
    been set , the user is welcomed by name -
    otherwise, the script is terminated with the PHP
    exit function.lt?php if (!isset(_SERVER'PHP_
    AUTH_USER')) header('WWW-Authent
    icate Basic
    realm"workgroup"') header('HTTP/1.0
    401 Unauthorized') echo 'Sorry, you are
    not authorized.' exit
    else echo "Welcome,
    _SERVER'PHP_AUTH_USER'." ?gt
Write a Comment
User Comments (0)
About PowerShow.com